【问题标题】:Multi option string color input validation?多选项字符串颜色输入验证?
【发布时间】:2023-03-30 06:13:01
【问题描述】:

我正在努力开发一个程序,该程序允许用户通过输入全色输出(不区分大小写)或作为颜色第一个字母的字符(不区分大小写)来选择两种颜色,具体取决于什么他们键入的颜色会自动将另一个分配给不同的变量。我的两个选项是蓝色和绿色,蓝色似乎工作正常,但是当我输入绿色或 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"))是无法访问的,直到你输入“blue”或“b”
  • @Jerry06 你是什么意思蓝色或 b 的输入必须达到绿色?

标签: java string char string-comparison ignore-case


【解决方案1】:

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

如果color 匹配choice,则只有matchesChoice 返回truefalse

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: ");
    }
}

【讨论】:

  • 我现在看到了错误。我已将此应用到我的代码中,并且程序现在正在运行。
猜你喜欢
  • 1970-01-01
  • 2016-06-12
  • 2012-05-10
  • 1970-01-01
  • 1970-01-01
  • 2011-12-17
  • 2015-04-29
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多