In Java, the invitation is repeated until all characters in the string are accepted

I am new to java and trying to make a Roman number calculator. I have basic encoding, but I want to add the ability to check for "illegal" characters on the main line.

I created a method called "ValidCheck" to check all characters in a string for a list of valid characters.

public static boolean ValidCheck(String letter){
    boolean okay = true;
    for (int i = 0; i < Letters.length; i++){
        if (Letters[i] != letter){
            okay = false;
        }
    }           
    return okay;
}

Here is the input from the user. I want to be able to print an error message, and then just repeat the original question until the line is acceptable, and ValidCheck == true.

System.out.print("Type in a Roman Numeral value: ");
String roman = kb.next();
for (int i = 0; i < roman.length(); i++){
    if (ValidCheck(roman.charAt(i) + "") == false){
        System.out.println("Error with input. Unexpected character.");      
    }
}

ex.

Type in a Roman Numeral : MMDK

Error with input. Unexpected character.

Type in a Roman Numeral : 

, , , ? , , , , , !

+4
1

java.util.Scanner . A Scanner .

:

import java.util.Scanner;

public class LoopingInput {
    public static void main(String[] args) {
        try (Scanner scanner = new Scanner(System.in)) {
            for (;;) {
                System.out.println("Type in a Roman Numeral value: ");
                String nextLine = scanner.nextLine();
                if (!nextLine.matches("[IVXLCDM]+")) {
                    System.out.println("Error with input. Unexpected character.");
                }
                // you may want to "return nextLine" or similar in an "else" branch
            }
        }
    }
}

:

  • try (...) {...} - Java-8, - -
  • System.in - -
  • scanner.nextLine() , ;
  • nextLine.matches("[IVXLCDM]+") . . (+) IVXLCDM.
+2

Source: https://habr.com/ru/post/1629627/


All Articles