在单行上提示多个输入

时间:2014-11-02 03:37:43

标签: java

我有一个问题。我知道你可以用扫描仪多次提示用户

public static void main(String[] args) {
        String First;
        String Last;
        int Age;
        Scanner input = new Scanner(System.in);
        System.out.print("What is the First name of person?");
        First = input.next();
        System.out.print("What is the Last name of person?");
        Last = input.next();  
        System.out.print("What is the Age of person?");
        Age = input.next(); 
}

但有没有办法在一行中提示所有人?

例如我想输入

Console-What is the First, Last, and Age of the person?
User- First Last Age

2 个答案:

答案 0 :(得分:1)

首先,Java变量按照惯例以小写字母开头(你的看起来像是类名)。第二,这个

Age = input.next();

给你一个编译器错误。因为Ageint。您当然可以像其他人建议的那样拆分单行,但您也可以构建一个Scanner(String)并将其用于类似

的内容
Scanner input = new Scanner(System.in);
System.out.println("Please enter the first name last name and age of the person: ");
System.out.println("(first last age)");
String line = input.nextLine();
Scanner scan = new Scanner(line);
String first = scan.next();
String last = scan.next();
int age = scan.nextInt();
System.out.printf("Person: %s, %s (%d)%n", last, first, age);

答案 1 :(得分:0)

抓一条线并拆分字符串:

Scanner input = new Scanner(System.in);
System.out.print("What is the First, Last, and Age of the person?");
String line = input.nextLine();
String[] parts = line.split(" ");
if(parts.length < 3){
    //error, ask again
}
else{
    String first = parts[0];
    String last = parts[1];
    String age = parts[2];
}