ในบทความนี้ เราจะเข้าใจวิธีการรับอินพุตจากผู้ใช้ในภาษา Java สิ่งนี้ทำได้โดยใช้วัตถุสแกนเนอร์ ใช้เมธอด Scanner.nextInt() เพื่อรับอินพุต
java.util.Scanner.nextInt() วิธีการสแกนโทเค็นถัดไปของอินพุตเป็น int การเรียกใช้เมธอดของรูปแบบ nextInt() นี้ทำงานในลักษณะเดียวกับการเรียกใช้ nextInt(radix) โดยที่ radix คือฐานเริ่มต้นของเครื่องสแกนนี้
ด้านล่างนี้เป็นการสาธิตสิ่งเดียวกัน -
ป้อนข้อมูล
สมมติว่าข้อมูลที่เราป้อนคือ −
Hello, I am John!
ผลผลิต
ผลลัพธ์ที่ต้องการจะเป็น −
The input string is: Hello, I am John!
อัลกอริทึม
Step1- Start Step 2- Declare a string: value Step 3- Prompt the user to enter a string Step 4- Read the values Step 5- Display the value Step 6- Stop
ตัวอย่างที่ 1
ที่นี่ ผู้ใช้ป้อนอินพุตตามข้อความแจ้ง คุณสามารถลองใช้ตัวอย่างนี้ในเครื่องมือกราวด์ของเรา
.
import java.util.Scanner;
public class PrintString{
public static void main(String[] args){
String value;
Scanner scanner = new Scanner(System.in);
System.out.println("A reader object has been defined ");
System.out.print("Enter a string: ");
value = scanner.nextLine();
System.out.println("The nextLine method is used to read the string value ");
System.out.println("The string is: ");
System.out.println(value);
}
} ผลลัพธ์
A reader object has been defined Enter a string: Good Morning! The nextLine method is used to read the string value The string is: Good Morning!
ตัวอย่างที่ 2
ที่นี่ ผู้ใช้ป้อนอินพุตตามข้อความแจ้งโดยใช้วัตถุ InputStreamReader
ที่นี่ ผู้ใช้ป้อนอินพุตตามข้อความแจ้ง คุณสามารถลองใช้ตัวอย่างนี้ในเครื่องมือกราวด์ของเรา
.
import java.io.*;
public class readNum{
public static void main(String args[]) throws IOException{
InputStreamReader read=new InputStreamReader(System.in);
System.out.println("An object of InputStreamReader class is created");
BufferedReader in=new BufferedReader(read);
System.out.println("A constructor of the BufferedReader class is created");
System.out.println("Enter a number: ");
int number=Integer.parseInt(in.readLine());
}
} ผลลัพธ์
An object of InputStreamReader class is created A constructor of the BufferedReader class is created Enter a number: 34