我正在努力使用一个程序让用户通过键入全颜色(不区分大小写)或字母的第一个字母(不区分大小写)来选择两种颜色,具体取决于什么它们键入的颜色会自动将另一个分配给另一个变量。我的两个选项是蓝色和绿色,蓝色似乎工作正常,但当我输入绿色或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循环,它确保用户选择一个颜色选择和一个方法来确定用户输入的String是否与问题的String选项匹配。
答案 0 :(得分:1)
else if(matchesChoice(color, "green"))
无法访问。当您输入matchesChoice(color, "blue")
或g
时,系统会调用green
方法,因此始终将其与b
或blue
进行比较。然后在该方法中,它会继续循环,因为您继续输入g
或green
。
如果true
与false
匹配,只需要匹配选项color
或choice
:
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;
}
然后在main中的while循环内添加用户输入的扫描:
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: ");
}
}