[java] Java에서 스캐너 클래스를 사용하여 콘솔에서 입력을 읽으려면 어떻게해야합니까?

Scanner클래스를 사용하여 콘솔에서 입력을 읽으려면 어떻게 해야합니까? 이 같은:

System.out.println("Enter your username: ");
Scanner = input(); // Or something like this, I don't know the code

기본적으로 원하는 것은 스캐너가 사용자 이름의 입력을 읽고 입력을 String변수에 할당하는 것 입니다.



답변

java.util.Scanner작품이에서 단일 정수를 읽는 방법을 설명하는 간단한 예 입니다 System.in. 정말 간단합니다.

Scanner sc = new Scanner(System.in);
int i = sc.nextInt();

사용자 이름을 검색하려면 아마 사용할 것입니다 sc.nextLine().

System.out.println("Enter your username: ");
Scanner scanner = new Scanner(System.in);
String username = scanner.nextLine();
System.out.println("Your username is " + username);

next(String pattern)입력을 더 많이 제어하거나 username변수의 유효성을 검사하려는 경우 에도 사용할 수 있습니다 .

구현에 대한 자세한 내용은 API 설명서를 참조하십시오.java.util.Scanner


답변

Scanner scan = new Scanner(System.in);
String myLine = scan.nextLine();


답변

콘솔에서 데이터 읽기

  • BufferedReader동기화되므로 여러 스레드에서 BufferedReader의 읽기 작업을 안전하게 수행 할 수 있습니다. 버퍼 크기를 지정하거나 기본 크기 ( 8192 )를 사용할 수 있습니다. 대부분의 경우 기본값은 충분히 큽니다.

    readLine () « 은 스트림이나 소스에서 한 줄씩 데이터를 읽습니다. 행은 다음 중 하나에 의해 종료 된 것으로 간주됩니다 : \ n, \ r (또는) \ r \ n

  • Scanner구분 기호 패턴을 사용하여 입력을 토큰으로 나눕니다. 구분 기호 패턴은 기본적으로 공백 (\ s)과 일치하며로 인식됩니다 Character.isWhitespace.

    « 사용자가 데이터를 입력 할 때까지 스캔 작업이 차단되어 입력을 기다릴 수 있습니다.
    « 스트림에서 특정 유형의 토큰을 구문 분석 하려면 스캐너 ( BUFFER_SIZE = 1024 )를 사용하십시오 .
    « 그러나 스캐너는 스레드 안전하지 않습니다. 외부 적으로 동기화되어야합니다.

    next ()«이 스캐너에서 다음 완전한 토큰을 찾아 반환합니다. nextInt ()«입력의 다음 토큰을 int로 스캔합니다.

암호

String name = null;
int number;

java.io.BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
name = in.readLine(); // If the user has not entered anything, assume the default value.
number = Integer.parseInt(in.readLine()); // It reads only String,and we need to parse it.
System.out.println("Name " + name + "\t number " + number);

java.util.Scanner sc = new Scanner(System.in).useDelimiter("\\s");
name = sc.next();  // It will not leave until the user enters data.
number = sc.nextInt(); // We can read specific data.
System.out.println("Name " + name + "\t number " + number);

// The Console class is not working in the IDE as expected.
java.io.Console cnsl = System.console();
if (cnsl != null) {
    // Read a line from the user input. The cursor blinks after the specified input.
    name = cnsl.readLine("Name: ");
    System.out.println("Name entered: " + name);
}

스트림의 입출력

Reader Input:     Output:
Yash 777          Line1 = Yash 777
     7            Line1 = 7

Scanner Input:    Output:
Yash 777          token1 = Yash
                  token2 = 777


답변

input.nextInt () 메소드에 문제가 있습니다. int 값만 읽습니다.

따라서 input.nextLine ()을 사용하여 다음 줄을 읽을 때 “\ n”, 즉 Enter키를받습니다. 따라서 이것을 건너 뛰려면 input.nextLine ()을 추가해야합니다.

그렇게 해보십시오.

 System.out.print("Insert a number: ");
 int number = input.nextInt();
 input.nextLine(); // This line you have to add (it consumes the \n character)
 System.out.print("Text1: ");
 String text1 = input.nextLine();
 System.out.print("Text2: ");
 String text2 = input.nextLine();


답변

사용자로부터 입력을받는 방법에는 여러 가지가 있습니다. 이 프로그램에서는 스캐너 클래스를 사용하여 작업을 수행합니다. 이 스캐너 클래스는 아래 java.util에 있으므로 프로그램의 첫 번째 행은 import java.util.Scanner입니다. 이를 통해 사용자는 Java에서 다양한 유형의 값을 읽을 수 있습니다. import 문은 자바 프로그램의 첫 번째 줄에 있어야하며 코드를 계속 진행해야합니다.

in.nextInt(); // It just reads the numbers

in.nextLine(); // It get the String which user enters

Scanner 클래스의 메소드에 액세스하려면 “in”으로 새 스캐너 오브젝트를 작성하십시오. 이제 그 방법 중 하나 인 “다음”을 사용합니다. “다음”메소드는 사용자가 키보드에 입력 한 텍스트 문자열을 가져옵니다.

여기서는 in.nextLine();사용자가 입력 한 문자열을 얻는 데 사용 하고 있습니다.

import java.util.Scanner;

class GetInputFromUser {
    public static void main(String args[]) {
        int a;
        float b;
        String s;

        Scanner in = new Scanner(System.in);
        System.out.println("Enter a string");
        s = in.nextLine();
        System.out.println("You entered string " + s);

        System.out.println("Enter an integer");
        a = in.nextInt();
        System.out.println("You entered integer " + a);

        System.out.println("Enter a float");
        b = in.nextFloat();
        System.out.println("You entered float " + b);
    }
}


답변

import java.util.Scanner;

public class ScannerDemo {
    public static void main(String[] arguments){
        Scanner input = new Scanner(System.in);

        String username;
        double age;
        String gender;
        String marital_status;
        int telephone_number;

        // Allows a person to enter his/her name   
        Scanner one = new Scanner(System.in);
        System.out.println("Enter Name:" );
        username = one.next();
        System.out.println("Name accepted " + username);

        // Allows a person to enter his/her age   
        Scanner two = new Scanner(System.in);
        System.out.println("Enter Age:" );
        age = two.nextDouble();
        System.out.println("Age accepted " + age);

        // Allows a person to enter his/her gender  
        Scanner three = new Scanner(System.in);
        System.out.println("Enter Gender:" );
        gender = three.next();
        System.out.println("Gender accepted " + gender);

        // Allows a person to enter his/her marital status
        Scanner four = new Scanner(System.in);
        System.out.println("Enter Marital status:" );
        marital_status = four.next();
        System.out.println("Marital status accepted " + marital_status);

        // Allows a person to enter his/her telephone number
        Scanner five = new Scanner(System.in);
        System.out.println("Enter Telephone number:" );
        telephone_number = five.nextInt();
        System.out.println("Telephone number accepted " + telephone_number);
    }
}


답변

간단한 프로그램을 만들어 사용자 이름을 요청하고 응답이 입력 한 내용을 인쇄 할 수 있습니다.

또는 사용자에게 두 개의 숫자를 입력하도록 요청하면 계산기의 동작과 같이 해당 숫자를 더하거나 곱하거나 빼거나 나누고 사용자 입력에 대한 답변을 인쇄 할 수 있습니다.

따라서 스캐너 클래스가 필요합니다. 당신은 import java.util.Scanner;해야하고 코드에서 사용해야합니다 :

Scanner input = new Scanner(System.in);

input 변수 이름입니다.

Scanner input = new Scanner(System.in);

System.out.println("Please enter your name: ");
s = input.next(); // Getting a String value

System.out.println("Please enter your age: ");
i = input.nextInt(); // Getting an integer

System.out.println("Please enter your salary: ");
d = input.nextDouble(); // Getting a double

방법이 다릅니다 참조 : input.next();, i = input.nextInt();,d = input.nextDouble();

String에 따르면 int와 double은 나머지와 같은 방식으로 다릅니다. 코드 상단에있는 import 문을 잊지 마십시오.