Nick Nick - 9 months ago 29
Java Question

Printing twice, not prompted for Scanner input

Iam working on some homework and an having an issue where once the user chooses an input to enter a sentence and the program writes "Please enter a sentence" it writes this twice when it should be once. Here is my code.

import java.util.Scanner;

public class ParseSentence{

public static void main(String []args){

Scanner sc = new Scanner(System.in);



int selection = -1;
String sentence = "";
boolean flag = true;

while(flag){


while(selection == -1){
System.out.print("Menu: \n 1. Enter a new sentence\n 2. Display the sentence in uppercase \n 3. count the number of words \n 4. count the number of vowels \n 5. Display the longest word in the sentence \n 0. Exit \n");
selection = sc.nextInt();
if(selection > 1){
if(sentence.equals("")){
System.out.println("Error please first enter a sentence");
selection =-1;
}
}
}

while(selection == 1){

System.out.println("Please enter a sentence");

sentence = sc.nextLine();

if(sentence.equals("")){
selection = 1;
}else
selection = -1;


}


if(selection == 2){
System.out.println(Upper(sentence));
selection = -1;
}

if(selection == 0)
break;

selection = -1;
}
}

public static String Upper(String s){
String morph = s.toUpperCase();

return morph;
}
}


The output looks like this


Menu:

1. Enter a new sentence

2. Display the sentence in uppercase

3. count the number of words

4. count the number of vowels

5. Display the longest word in the sentence

0. Exit

1

Please enter a sentence

Please enter a sentence



I tried to replicate the bug in another program to see if I am doing something wrong with while loop but I am stumped. thanks for help.

Answer Source

After the last sc.nextInt(), on the line where you entered 1 the terminating newline character is not yet read. It will be read in the first iteration of your while loop. That is, sentence = sc.nextLine() will be empty at first, and the loop body will be executed one more time.

One simple solution is to add a sc.nextLine() right before the loop.

// read terminating newline that remained after last int input
sc.nextLine();

while (selection == 1) {
    System.out.println("Please enter a sentence");
    sentence = sc.nextLine();

    if (sentence.equals("")) {
        selection = 1;
    } else {
        selection = -1;
    }
}