0

I have one problem. Neither of these work for my code.

When running this code with

sodaType = keyboard.next();

userInput (called sodaType in code) only saves the first part of "Root Beer", outputting ("Root").

I googled the problem and

sodaType = keyboard.nextLine();

Allows for "white space", but skips the userInput, outputting nothing, skipping the if statement.

I found different answers on this site

I am confused on why the nextLine() worked for them, and how I should continue.

while(true) {
        System.out.println("Please enter a brand of soda. ");
        System.out.print("You can choose from Pepsi, Coke, Dr. Pepper, or Root Beer: ");
        sodaType = keyboard.next();
        System.out.println("sodatype" + sodaType);
        if (sodaType.equalsIgnoreCase("pepsi") || sodaType.equalsIgnoreCase("coke") || 
                sodaType.equalsIgnoreCase("dr pepper") || sodaType.equalsIgnoreCase("dr. pepper") || 
                sodaType.equalsIgnoreCase("root beer")) 
        {
            System.out.println("you chose " +  sodaType);
            break;
        }
        else {
            System.out.println("Please enter an avaiable brand of soda. ");

        }
    }
  • `outputting nothing, skipping the if statement` are you sure you pressed enter after the input? – MDK Oct 26 '20 at 19:50

2 Answers2

0

That's because scanners work by separating the input into a sequence of 'tokens' and 'delimiters'. Out of the box, 'one or more whitespace characters' is the delimiter, thus, an input of:

Root Beer
Hello World
5

consists of 5 tokens: [Root, Beer, Hello, World, 5]. What you want is that this forms 3 tokens: [Root Beer, Hello World, 5].

Easy enough: Tell the scanner you intend for newlines to be the delimiter, and not just any whitespace:

Scanner s = new Scanner(System.in);
s.useDelimiter("\r?\n");

That's a regular expression that will match newlines regardless of OS.

Mixing nextLine() with any other next method in scanner leads to pain and suffering, so, don't do that. Forget nextLine exists.

rzwitserloot
  • 85,357
  • 5
  • 51
  • 72
-1

So When you write .next() this function reads String and read until it encounters a white space
So when you write this and give input as root beer it will read-only root cause after that root there's a white space which tells java to stop reading cause may be user wants to end the read.

sodaType = keyboard.next();

That's the reason why .nextLint() is introduce cause it will read the whole line as it is including white spaces. So when you write and gave input like root beer

sodaType = keyboard.nextLine();

it will store it as root beer
and if you gave input as root beer it will store it as root beer
NOTE: the exact number of white spaces.

Swapnil Padaya
  • 687
  • 5
  • 14