[java] Java : System.console ()에서 입력을 얻는 방법

콘솔 클래스를 사용하여 사용자로부터 입력을 얻으려고하지만 호출 할 때 null 객체가 반환됩니다 System.console(). System.console을 사용하기 전에 변경해야합니까?

Console co=System.console();
System.out.println(co);
try{
    String s=co.readLine();
}



답변

콘솔을 사용하여 입력 읽기 (IDE 외부에서만 사용 가능) :

System.out.print("Enter something:");
String input = System.console().readLine();

다른 방법 (모든 곳에서 작동) :

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Test {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        System.out.print("Enter String");
        String s = br.readLine();
        System.out.print("Enter Integer:");
        try {
            int i = Integer.parseInt(br.readLine());
        } catch(NumberFormatException nfe) {
            System.err.println("Invalid Format!");
        }
    }
}

IDE에서 System.console ()은 null을 반환합니다.
따라서 실제로 사용해야하는 경우 McDowellSystem.console() 에서이 솔루션을 읽으십시오 .


답변

Scanner in = new Scanner(System.in);

int i = in.nextInt();
String s = in.next();


답변

콘솔 / 키보드에서 입력 문자열을 읽는 방법은 거의 없습니다. 다음 샘플 코드는 Java를 사용하여 콘솔 / 키보드에서 문자열을 읽는 방법을 보여줍니다.

public class ConsoleReadingDemo {

public static void main(String[] args) {

    // ====
    BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
    System.out.print("Please enter user name : ");
    String username = null;
    try {
        username = reader.readLine();
    } catch (IOException e) {
        e.printStackTrace();
    }
    System.out.println("You entered : " + username);

    // ===== In Java 5, Java.util,Scanner is used for this purpose.
    Scanner in = new Scanner(System.in);
    System.out.print("Please enter user name : ");
    username = in.nextLine();
    System.out.println("You entered : " + username);


    // ====== Java 6
    Console console = System.console();
    username = console.readLine("Please enter user name : ");
    System.out.println("You entered : " + username);

}
}

사용 된 코드의 마지막 부분 java.io.Console 클래스를 . System.console()Eclipse를 통해 데모 코드를 실행할 때 콘솔 인스턴스를 가져올 수 없습니다 . Eclipse는 애플리케이션을 시스템 콘솔을 사용하는 최상위 프로세스가 아닌 백그라운드 프로세스로 실행하기 때문입니다.


답변

환경에 따라 다릅니다. 당신이를 통해 스윙 UI 실행하는 경우 javaw예를 들어, 다음이 되지 않습니다 표시 할 콘솔 . IDE 내에서 실행중인 경우 특정 IDE의 콘솔 IO 처리에 크게 의존합니다.

명령 줄에서 괜찮을 것입니다. 견본:

import java.io.Console;

public class Test {

    public static void main(String[] args) throws Exception {
        Console console = System.console();
        if (console == null) {
            System.out.println("Unable to fetch console");
            return;
        }
        String line = console.readLine();
        console.printf("I saw this line: %s", line);
    }
}

다음과 java같이 실행하십시오 .

> javac Test.java
> java Test
Foo  <---- entered by the user
I saw this line: Foo    <---- program output

또 다른 옵션은 사용하는 것입니다 System.in당신이에 포장 할 수 있습니다, BufferedReader선, 또는 사용 읽기 Scanner(다시 포장을 System.in).


답변

콘솔에서 읽는 것에 관한 좋은 대답을 찾았습니다. 또 다른 방법은 ‘스캐너’를 사용하여 콘솔에서 읽는 것입니다.

import java.util.Scanner;
String data;

Scanner scanInput = new Scanner(System.in);
data= scanInput.nextLine();

scanInput.close();
System.out.println(data);


답변

이 시도. 이것이 도움이되기를 바랍니다.

    String cls0;
    String cls1;

    Scanner in = new Scanner(System.in);
    System.out.println("Enter a string");
    cls0 = in.nextLine();

    System.out.println("Enter a string");
    cls1 = in.nextLine(); 


답변

다음은 athspk의 답변을 취하여 사용자가 “종료”를 입력 할 때까지 계속 반복되는 답변 으로 만듭니다. 또한 이 코드를 가져 와서 테스트 할 수 있는 후속 답변을 작성 했습니다.

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class LoopingConsoleInputExample {

   public static final String EXIT_COMMAND = "exit";

   public static void main(final String[] args) throws IOException {
      BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
      System.out.println("Enter some text, or '" + EXIT_COMMAND + "' to quit");

      while (true) {

         System.out.print("> ");
         String input = br.readLine();
         System.out.println(input);

         if (input.length() == EXIT_COMMAND.length() && input.toLowerCase().equals(EXIT_COMMAND)) {
            System.out.println("Exiting.");
            return;
         }

         System.out.println("...response goes here...");
      }
   }
}

출력 예 :

Enter some text, or 'exit' to quit
> one
one
...response goes here...
> two
two
...response goes here...
> three
three
...response goes here...
> exit
exit
Exiting.