YummyTree
YummyTree

Reputation: 59

Prompting Multiple inputs on a Single line

I have a question. I know you can prompt a user multiple times with scanner as so

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(); 
}

But is there a way there to prompt all in one line?

For example I want to enter

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

Upvotes: 2

Views: 1375

Answers (2)

Elliott Frisch
Elliott Frisch

Reputation: 201409

First, Java variables start with a lower case letter by convention (yours look like class names). Second, this

Age = input.next();

gives you a compiler error. Because Age is an int. You can certainly split the single line as others have suggested, but you can also construct a Scanner(String) and use it with something like

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);

Upvotes: 1

Grab a line and split the string:

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];
}

Upvotes: 0

Related Questions