打印两次,不提示输入扫描仪

时间:2017-03-12 06:37:22

标签: java

我正在做一些家庭作业,并且遇到一个问题,一旦用户选择输入输入一个句子并且程序写入"请输入一个句子"当它应该是一次时,它会写两次。这是我的代码。

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;
    }
}

输出看起来像这样

 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

我试图在另一个程序中复制这个bug,看看我是否在做while循环时出错了但是我很难过。谢谢你的帮助。

1 个答案:

答案 0 :(得分:0)

在最后sc.nextInt()之后,在您输入1的行上,尚未读取终止换行符。 它将在while循环的第一次迭代中读取。 也就是说,sentence = sc.nextLine()最初会为空, 并且循环体将再次执行。

一个简单的解决方案是在循环之前添加sc.nextLine()

// 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;
    }
}