Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Looping multiple scanner inputs until a specific input

I am new to java, and I am doing this assignment for a romanCalculator. I am currently doing with the calculation part but i am having an issue with some of the rules requested.

If the input is incorrect, an error has to be printed.

So this is one of the rules, and these are the only possible inputs.

<possible Roman number> <operator> <possible Roman number>

OR

<possible Roman number> <operator> <possible Roman number>

OR

.

The first 2 are easy to understand, and the . is to exit the program.

This is all what i could do with my knowledge:

Scanner in = new Scanner(System.in);

    String firstRoman = in.next();
    String operator = in.next();
    String secondRoman = in.next();

It just asks once and only 1 form of input. I can't figure out how to apply this to what is requested, I'd appreciate any help. Thanks!

Here is an example:

\begin{ipoutput} XX \end{ipoutput}
\begin{ipinput} *xii

\begin{ipinput} /vi \end{ipinput}
\begin{ipoutput} XL

\begin{ipoutput} MCDXLV \end{ipoutput}
\begin{ipinput} .
like image 899
Lenotre Avatar asked Nov 19 '25 08:11

Lenotre


1 Answers

    Scanner in = new Scanner(System.in);
    String input = "";
    System.out.println("Enter your roman numbers\nEx: X + V\n:");
    while(!(input = in.nextLine()).equals("."))
    {
        //assuming splitting the input around whitespace we can do the following
        String[] userInput = input.split("\\s+");
        if(userInput.length == 3)
        {
            String firstRoman = userInput[0];
            String operator = userInput[1];
            String secondRoman = userInput[2];
            if(firstRoman.matches("[MCDXLV]+") && operator.matches("\\+|\\-") && secondRoman.matches("[MCDXLV]+"))
            {
                //we have some valid things to work with let's continue
                System.out.println("Valid input - " + input);
            }
            else{
                System.out.println("Invalid input - " + input);
            }
            //do your thing
        }
        else{
            System.out.println("Invalid input - " + input);
        }
        System.out.println("Enter your roman numbers\nEx: X + V\n:");
    }
like image 146
RAZ_Muh_Taz Avatar answered Nov 21 '25 22:11

RAZ_Muh_Taz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!