何らかの宿題に取り組んでいて、ユーザーが文章を入力するための入力を選択して「文章を入力してください」と書いてしまうと、一度。ここに私のコードです。2度印刷するとスキャナの入力が要求されない
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を加えます。 nextLine() 'を使用すると、リターン文字を使用できます。 – SMA
Java!= JavaScript(タグを削除しました) – nnnnnn