Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial

Luke Glazebrook
13,564 PointsProblem with .nextLine() in Java.
I am writing this program to solve difficult decisions for me and it works fine except for one thing. When I input two words like "Toffee Crisp" it automatically takes that as being all the decisions and I can't figure out why. Any help would be greatly appreciated!
package mainPackage;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.Random;
public class App {
static Scanner s = new Scanner(System.in);
static Random rn = new Random();
public static void main(String args[]) {
List<String> options = new ArrayList<String>();
System.out.println("How many options does your decision require? ");
int optionsRequired = s.nextInt();
for(int i = 0; i < optionsRequired; i++) {
System.out.print("Enter your option: ");
String option = s.next();
options.add(option);
}
int answer = rn.nextInt(optionsRequired);
System.out.println("The program chose " + options.get(answer));
}
}
2 Answers

Craig Dennis
Treehouse TeacherHi Luke!
Scanner.next() grabs the next token specified by the delimiter, by default it is whitespace (such as space). Maybe you want to be using nextLine()?
Hope it Helps!

Craig Dennis
Treehouse TeacherOh I see the problem now Luke.
First, use nextLine instead of next. The other fix is to call a nextLine() before you start prompting for the options. This is because nextInt does not swallow the newline character.
Here is a Stack Overflow answer explaining the problem.
Hope it helps!

Luke Glazebrook
13,564 PointsThanks for the awesome help Craig I appreciate it a lot!
I shall implement the solution and see how it goes but I have no doubt that everything should be working fine!
-Luke
Luke Glazebrook
13,564 PointsLuke Glazebrook
13,564 PointsHi Dennis!
Thank you for the reply I really appreciate it. I have already tried using .nextLine() thinking that would help scan the rest of the text after the first word but I still experience a similar issue.
-Luke