javastringcharstring-comparisonignore-case

Multi option string color input validation?


I'm struggling with a program that lets a user chose between two color by typing either the full color out (not case sensitive ) or a char that is the first letter of the color (not case sensitive), depending on what color they type it will automatically assign the other to a different variable. My two options are blue and green, blue seems to be working fine but when I input green or g the method keeps asking me for a new input. Here is a snip of my program that deals with the color assignment.

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;

  }

}

I'm basically creating a while loop that insures the user selects one of the color choices and a method to determine whether a String input by the user matches a String option for the question.


Solution

  • The else if(matchesChoice(color, "green")) is unreachable. The matchesChoice(color, "blue") method is being called when you enter g or green, so it's always comparing it against b or blue. Then within that method, it continues to loop because you keep entering g or green.

    Just have matchesChoice return true or false if color matches 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;
    }
    

    Then add the scan for user input inside of the while loop in main:

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