4

I'm fairly new to java and trying to make a roman numeral calculator. I have the main coding done but I want to add the ability to check for "illegal" characters in the main string.

I have created a method called "ValidCheck" to test all chars in the string against a list of acceptable 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 string 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 : 

I'm wondering how I can put this into a loop to ask repeatedly until the input is deemed acceptable using the method? Also since I'm fairly new an explanation of how it is repeating and how the value is returned from the loop would be greatly appreciated!

Let'sRefactor
  • 3,303
  • 4
  • 27
  • 43
  • 6
    `if (Letters[i] != letter){` -> [How do I compare strings in Java?](http://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java) – Pshemo Feb 19 '16 at 21:56

1 Answers1

2

I recommend using a java.util.Scanner in combination with an endless loop. A Scanner is easy to use and solves many of the common tasks.

An example code could look like this:

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
            }
        }
    }
}

explanation:

  • try (...) {...} is a Java-8 feature, that will automatically close an object - even if something unexpected happens
  • System.in is the default input - and in most cases that is the command line or a file input
  • scanner.nextLine() waits for the user to enter a new line; and returns that line
  • nextLine.matches("[IVXLCDM]+") is using a regular expression to validate your input. That's quite handy in such situations. It searches for any number (+) of IVXLCDM characters.
slartidan
  • 20,403
  • 15
  • 83
  • 131