이 기사에서는 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