我正在努力使用一个程序,该程序允许用户通过输入全色输出(不区分大小写)或作为颜色第一个字母的字符(不区分大小写)来选择两种颜色,具体取决于他们输入的颜色它会自动将另一个分配给不同的变量。我的两个选项是蓝色和绿色,蓝色似乎工作正常,但是当我输入绿色或 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 循环,以确保用户选择一种颜色选择和一种方法来确定用户输入的字符串是否与问题的字符串选项匹配。