gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 11:41:18 25 4
gpt4 key购买 nike

我正在做一些作业,遇到一个问题,一旦用户选择输入来输入一个句子,程序会写“请输入一个句子”,它会在应该写一次的情况下写两次。这是我的代码。

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

我尝试在另一个程序中复制该错误,看看我是否在 while 循环中做错了什么,但我被难住了。感谢您的帮助。

最佳答案

在最后一个 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;
}
}

关于java - 打印两次,不提示扫描仪输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42744542/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com