简体   繁体   中英

In Java, I am trying to validate input by checking for invalid input. Somehow it is not correctly returning an error

First off, let me give you a small description of what I'm trying to do. For an assignment for college I have to recreate the game Mastermind in Java. So far everything's been going well, untill I came to a specific point in validating the user's input. I have an array of Strings called colorList, this list is filled with letters A to F (these are subtitutes for colors.)

When the user makes a guess, he enters a 4 letter code, for example ABCD. What I want to make sure is that every character in the guess is also contained in the colorList array to prevent users from guessing 'colors' that do not exist.

The code I'm using to validate this is as followed:

    boolean incorrectInput = true;
    while (incorrectInput) {
        boolean ooitgoed = false;
        outerloop: for (int a = 0; a < code.length(); a++) { // Select next letter in input.
            for (int i = 0; i < colorList.size(); i++) { // Select next element in array to compare to.
                ooitgoed = false; // Will put the boolean on false for as long as it does not find the selected char in the array.
                if (colorList.get(i).charAt(0) == code.charAt(a)) { // If selected input character is equal to selected element from array:
                    System.out.println("Code char: " + code.charAt(a) + " - " + "Element from array: " + colorList.get(i) + " - correct input");
                    ooitgoed = true;
                    incorrectInput = false;
                    break; // Break out of the for-loop, which causes the next character of the input to be selected and then compared to every element in the array.
                }
            }

            if (ooitgoed == false) { // If the selected char is never found in the array, the boolean will still be false and a new input will be requested.
                System.out.println("Found incorrect input! Please only use 'A', 'B', 'C', 'D', 'E', or 'F'.");
                System.out.println("Enter your guess: ");
                input = in.next();
                input = input.toUpperCase();
                incorrectInput = true;
                break outerloop; // Break back to outerloop, re-executing the entire validation process with the new input requested above. 
            }
        }
    }

I added some commentary to explain a couple of procedures during the code that SHOULD be working, and I'm not able to find why it's not working.

The output I get when I execute the program and take a guess is as followed:

Code = DCFF

Enter your guess: DCFU

Code char: D - Element from array: D - correct input

Code char: C - Element from array: C - correct input

Code char: F - Element from array: F - correct input

Code char: F - Element from array: F - correct input

The U should have been found as invalid input, but somehow the program thinks it's an F and proceeds to validate it as such.

I added some commentary to explain a couple of procedures during the code that SHOULD be working, and I'm not able to find why it's not working.

If you need more info regarding my code please let me know, I'll provide you with as much as I need. I hope anyone can figure it out.

Thanks!

You are testing characters from code in your incorrectInput loop. Should be input .

Also a few comments about your code:

  • You don't need both ooitdoed and incorrectInput , either one is enough to hold your condition.

  • The outerloop is actually inner :) And you don't need that label - just break , without label will do.

  • Do not write boolean checks like if (ooitgoed == false) - just if(!ootitgoed)

  • You might find your implementation more clean and readable, if you make colorList a string "ABCDEF" instead of the array, and replace your innermost loop with incorrectInput = colorList.indexOf(input.charAt(a)) == -1

  • You can also validate the whole string at once, without any procedural loops with a regular expression: incorrectInput = !input.toUpperCase.matches("[AF]+") . Or, if you want to also report which character was wrong:

     Pattern p = Pattern.compile("[^AF]", Pattern.CASE_INSENSITIVE); // Do this before all loops // ... Matcher m = p.matcher(input); incorrectInput = m.find(); if(incorrectInput) System.out.println("This symbol is invalid: " + m.group()); 

First, let's create a method to validate the characters . Let's call it isCharValid :

public boolean isCharValid(char ch, List<String> list) {
  for (String s : list) {
    if (s.charAt(0) == ch) {
      return true;
    }
  }

  return false;
}

Now, change your code to:

while (true) {
  String input = in.next().toUpperCase();
  boolean validated = true;

  for (char ch : input.toCharArray()) {
    if (!isCharValid(ch, YOUR_COLOR_LIST)) {
      validated = false;
      break;
    }
  }

  if (validated) {
    // The input is OK!
  }
  else {
    System.out.println("Invalid output. Please, try again.");
    // Now it will go back to the beginning of the while-loop.
  }
}

General pointer: Make use of List s.

final List<Character> allowedInputs = new ArrayList<>();
allowedInputs.add('A');
allowedInputs.add('B');
allowedInputs.add('C');
allowedInputs.add('D');

final String input = getInput(); //gets the input from the user..

final char[] inputChars = input.toCharArray();

for (final char inputChar : inputChars) {
    if (allowedInputs.contains(inputChar)) {
        //All good
    } else {
       //Error in input!
}

This is a shorter way to do what you want:

private static final char[] COLORS = {'A', 'B', 'C', 'D', 'E', 'F'};


public static void main(String args[]) throws IOException {
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

    String input;
    boolean inputOk;

    do {
        inputOk = true;

        // read the input
        System.out.print("Enter your guess: ");
        input = br.readLine().toUpperCase();

        // do the check
        for (int i = 0; i < input.length() && inputOk; i++) {
            for (int j = 0; j < COLORS.length; j++) {
                if (input.charAt(i) == COLORS[j])
                    break;
                if (j == COLORS.length - 1)
                    inputOk = false;
            }
        }

        // input isn't ok
        if (!inputOk)
            System.out.println("Found incorrect input! Please only use 'A', 'B', 'C', 'D', 'E', or 'F'.");
    } while (!inputOk);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM