控制台上的输入不适用于这个java程序 - 为什么?

时间:2011-02-20 20:07:07

标签: java java.util.scanner

使用此程序,它会跳过输入 - 并将其输出到控制台:

    C:\Users\User\workspace\ClassManager\bin>java AccessPupilData
What would you like to do?
l = list pupils -------- a = add pupil ---------
a
a
You want to add a pupil.
Enter your first name:
Enter your surname:
Firstname :null
Surname: null
Age :0
You created a pupil called null null who is aged 0

(我正在使用dos提示符来运行程序,而不是eclipse控制台)。 调用扫描仪时为什么不输入?

首先开始一切的初始课程:

public class AccessPupilData {

public static void main (String arguments[]){

...

case 'a': Pupil pupil = new Pupil(); break;

然后是我想收集所有信息的Pupil课程:

import java.util.Scanner;

public class Pupil {
    private String surname;
    private String firstname;
    private int age;

public Pupil(){

    Scanner in = new Scanner(System.in);


       // Reads a single line from the console 
       // and stores into name variable
       System.out.println("Enter your first name: ");
       if(in.hasNext()){
           this.firstname = in.nextLine();
       }

       System.out.println("Enter your surname: ");
       if(in.hasNext()){
           this.surname = in.nextLine();
       }
       // Reads a integer from the console
       // and stores into age variable
       if(in.hasNext()){ 
       System.out.println("Enter your age: ");
       this.age=in.nextInt();
       }
       in.close();            

       // Prints name and age to the console

       System.out.println("Firstname :" +firstname);
       System.out.println("Surname: " + surname);
       System.out.println("Age :"+ age);


    System.out.print("You created a pupil called " + this.firstname + " " + this.surname + " who is aged " + this.age);
}

}

2 个答案:

答案 0 :(得分:1)

使用Console.readLine

Console c = System.console();
this.firstname = c.readLine("Enter your first name: ");

答案 1 :(得分:0)

我建议使用BufferedReader

Scanner is definitely very convenient to use but it is slower since it has to read the content of the stream every time next token in the stream is requested. While Buffered Reader buffers the tokens so that there is no need to read from the stream again. 引自Scanner vs BufferedReader

public static void main(String[] args) {
    String firstName = getInput("Enter your first name: ");
    System.out.println("Hello " + firstName);
}

public static String getInput(String prompt) {
    BufferedReader in = new BufferedReader(
            new InputStreamReader(System.in));

    System.out.print(prompt);
    System.out.flush();

    try {
        return in.readLine();
    } catch (IOException e) {
        return "Error: " + e.getMessage();
    }

}