The method next()
from the class Scanner will return only the next token.
As written in the oracle docu:
Finds and returns the next complete token from this scanner. A
complete token is preceded and followed by input that matches the
delimiter pattern. This method may block while waiting for input to
scan, even if a previous invocation of hasNext() returned true.
The default delimiter ist a space, so if your band name will contain more then one word, it will not work.
For reading a whole line of input user nextLine()
If you want to have both band names separatly, call nextLine()
twice to get each input separatly:
System.out.println("What are your favorite two bands?");
String band1 = scan.nextLine();
String band2 = scan.nextLine();
System.out.println("I like >>" + band1 + " and " + band2 + "<<too!");
In this case the user has to press 'enter' after each input.
EDIT:
As mentioned in the comment of Elliott Frisch, other readXXX methods will not remove the lineendings from the inputstream.
see:
stackoverflow.com/q/13102045/2970947
You can use nextLine() for every input or remove the lineending after each reading. Sample with your code:
Scanner scan = new Scanner(System.in);
System.out.println("What is your name?");
String name;
name = scan.next();
scan.nextLine();
System.out.println("Hello " + name);
System.out.println("What is your age?");
int years;
years = scan.nextInt();
scan.nextLine();
int ageInMonths;
ageInMonths = years * 12;
System.out.print("Your age is ");
System.out.print(ageInMonths);
System.out.println(" in months");
System.out.println("What are your favorite two bands?");
String bands = scan.nextLine();
System.out.println("I like >>" + bands + "<<too!");
API References:
next()
nextLine()