2017-03-12 8 views
1

何らかの宿題に取り組んでいて、ユーザーが文章を入力するための入力を選択して「文章を入力してください」と書いてしまうと、一度。ここに私のコードです。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ループと間違って何かをやっているかどうかを確認するために別のプログラムのバグを複製しようとしたが、私は困惑しています。手伝ってくれてありがとう。

+0

' SCを加えます。 nextLine() 'を使用すると、リターン文字を使用できます。 – SMA

+0

Java!= JavaScript(タグを削除しました) – nnnnnn

答えて

0

最後のsc.nextInt()の後、1を入力した行で、終端改行文字はまだ読み取られていません。 whileループの最初の繰り返しで読み込まれます。 つまり、最初にsentence = sc.nextLine()が空になり、 となり、ループ本体がもう一度実行されます。

単純な解決策の1つは、ループの直前にsc.nextLine()を追加することです。 `使用`選択= Integer.parseInt(sc.nextLine()); ``または選択= sc.nextInt(後に)、代わりに、 `選択= sc.nextInt()の

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

ありがとうございました! – Nick

関連する問題