0

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

4

1 回答 1

1

else if(matchesChoice(color, "green"))是无法到达的。输入or时会调用该matchesChoice(color, "blue")方法,因此它总是将其与or进行比较。然后在该方法中,它会继续循环,因为您不断输入or 。ggreenbblueggreen

只需返回 matchesChoicetruefalseifcolor匹配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: ");
    }
}
于 2016-11-15T02:34:11.790 回答