2016-11-15 2 views
0

私は、ユーザがフルカラー出力(大文字と小文字を区別しない)または色の最初の文字(大文字と小文字を区別しない)のどちらかをタイプすることによって2色の間で色を選択できるようにするプログラムに苦労しています彼らは自動的に他の変数に他のものを割り当てます。私の2つのオプションは青と緑で、青はうまく動作しているようですが、緑またはgを入力すると、メソッドは新しい入力を要求し続けます。ここでは、色の割り当てを扱う私のプログラムの切り札です。複数のオプション文字列の色入力の検証ですか?

import java.util.*; 
public class Test{ 
    public static Scanner in = new Scanner (System.in); 
    public static void main(String []args){ 

    System.out.println("Chose and enter one of the following colors (green or blue): "); 
    String color = in.next(); 
    boolean b = false; 
    while(!b){ 
     if(matchesChoice(color, "blue")){ 
     String circle = "blue"; 
     String walk = "green"; 
     b = true; 
     } 
     else if(matchesChoice(color, "green")){ 
     String circle = "green"; 
     String walk = "blue"; 
     b = true; 
     } 
    }  

    } 
    public static boolean matchesChoice(String color, String choice){ 
    String a= color; 
    String c = choice; 
    boolean b =false; 
    while(!a.equalsIgnoreCase(c.substring(0,1)) && !a.equalsIgnoreCase(c)){ 
     System.out.println("Invalid. Please pick green or blue: "); 
     a = in.next(); 
    } 
    b = true; 
    return b; 

    } 

} 

私は基本的にユーザーが色の選択及びユーザによる文字入力が質問の文字列オプションと一致するかどうかを決定するための方法のいずれかを選択保証whileループを作成しています。

+0

public static boolean matchesChoice(String color, String choice){ String a= color; String c = choice; if (a.equalsIgnoreCase(c.substring(0,1)) || a.equalsIgnoreCase(c)) { return true; } return false; } 

そして、メインでwhileループの内部にユーザー入力のためのスキャンを追加します。colorマッチchoiceがあれば

ちょうどmatchesChoiceはtrueまたはfalseを返してきましたあなたが青またはbを入力するまで、else if(matchesChoice(color、 "green")) 'が到達不能になる – Jerry06

+0

@ Jerry06緑に達するために青またはbの入力が必要であることを意味しますか? –

答えて

1

else if(matchesChoice(color, "green"))には到達できません。 gまたは​​と入力するとmatchesChoice(color, "blue")メソッドが呼び出されるため、常にbまたはblueと比較しています。その方法では、gまたは​​と入力し続けるので、ループし続けます。あなたのコードの流れがないので

boolean b = false; 
System.out.println("Chose and enter one of the following colors (green or blue): "); 
while(!b){ 
    String color = in.next(); 
    if(matchesChoice(color, "blue")){ 
     String circle = "blue"; 
     String walk = "green"; 
     b = true; 
    } 
    else if(matchesChoice(color, "green")){ 
     String circle = "green"; 
     String walk = "blue"; 
     b = true; 
    } 
    else { 
     System.out.println("Invalid. Please pick green or blue: "); 
    } 
} 
+0

私は間違いを今見ます。私はこれを私のコードに適用し、プログラムは今働いています。 –

関連する問題