多选项字符串颜色输入验证?

Multi option string color input validation?

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

无法访问 else if(matchesChoice(color, "green"))。当您输入 ggreen 时,将调用 matchesChoice(color, "blue") 方法,因此它始终将其与 bblue 进行比较。然后在该方法中,它继续循环,因为您不断输入 ggreen.

只要匹配选择 return truefalse 如果 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: ");
    }
}