0

I am building the framework for a fraction calculator in my AP CS class. I have figured everything out besides how to get it telling you that your input is invalid.
The kind of input that is acceptable is 2_2/3 + 4/5 or 4/6 - 2/5 but I want it to give an error if letters or more than two fractions are entered. Here is what I have, but it only seems to work with letters and not with numbers. I got 13 from the length of the maximum valid fractions I want. Ex. 2_2/4 + 3_4/5

if (inputLength >= 13) {
    System.out.println("Your Input is too long");
}
3
  • I don't really fully understand what you're doing. Can you provide some more code? Commented Oct 7, 2013 at 22:08
  • You could use a regex to check if the input matches your desired format. Commented Oct 7, 2013 at 22:13
  • 1
    Do the posted responses answer your question? Commented Feb 23, 2014 at 16:53

2 Answers 2

3

Another way to validate your input is using a regex. I suggest you to take a look at any Java regex tutorial or refer to official doc.

I know that at first sight regex can be really terrifying (and even more if you are learning how to program) but it is really useful and worth learning. In order to figure out the pattern you going to need to validate the user input, you can use online validator as rubular or java-regex-tester.

Sign up to request clarification or add additional context in comments.

Comments

0

As others have said, use regex. After writing your regex statement using some of the links Trein provided, you can call String.matches(String regex) to apply it.

For example:

if (inputString.matches("Your regex string here")) {
    // Parse input
} else {
    System.out.println("Invalid input!");
}

As a side note, regex is probably also the best way to parse the input. See The Java Tutorials (specifically "Capturing Groups") for more info on that and regex in general.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.