I am having trouble to get multiple inputs from the user using Java scanner.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
System.out.println("How old are you?? ");
//get an input from the user
Scanner scanner = new Scanner(System.in);
//put the user-input into a variable
int age = scanner.nextInt();
System.out.println("My age is "+ age + ".");
//get and put it in another variable
System.out.println("What's your name?");
String name = scanner.next();
name.strip();
System.out.println(name +"'s age is "+ age +".");
//Asking another question
System.out.println("What's your hobby?");
//get and put it in another variable
String hobby = scanner.nextLine();
System.out.println(name + "'s hobby is "+ hobby);
}
}
this is my code. it works fine with the first two inputs, but for the third input, it doesn't ask me to write, but just execute the code till the end and finish the work.
And I searched some postings related to this situation and found that the next() method will not take the Enter (\n) and this part will be leftover for the next input.
Therefore, I added a line for removing the whitespace of the variable 'name', so that the '\n' part is removed.
However, this will not solve the problem.
my result is like below
How old are you??
25
My age is 25.
What's your name?
Jason
Jason's age is 25.
What's your hobby?
Jason's hobby is .
Process finished with exit code 0
Why is '\n' still remain after stripping the string? and how can I fix it?
P.S. I want it to be nextLine() but not next() for the last input because the answer of the last input can be more than one word like "playing basketball".