ユーザーが入力する色に応じて、フルカラーアウト(大文字と小文字を区別しない)または色の最初の文字である文字(大文字と小文字を区別しない)のいずれかを入力して、ユーザーが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;
}
}
基本的に、ユーザーが色の選択肢の 1 つを選択することを保証する while ループと、ユーザーによる文字列入力が質問の文字列オプションと一致するかどうかを判断するメソッドを作成しています。