循环多个扫描器输入直到特定输入

3
我是Java的新手,正在为罗马计算器完成此任务。我目前在处理计算部分,但是我遇到了一些规则方面的问题。 如果输入不正确,则必须打印错误信息。 这是其中一个规则,以下是唯一可能的输入方式。
<possible Roman number> <operator> <possible Roman number>

或者

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

或者

.

前两个很容易理解,而 . 是退出程序的意思。

这是我根据我的知识所能做到的全部内容:

Scanner in = new Scanner(System.in);

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

它只需要一次输入和一种形式的输入。

我不知道如何将其应用于所需的内容,我会感激任何帮助。谢谢!

这是一个例子:

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

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

\begin{ipoutput} MCDXLV \end{ipoutput}
\begin{ipinput} .
1个回答

2
    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:");
    }

非常感谢您的帮助,但是我写错了第二个可能的选项。应该是这样的。 - undefined
就像这个例子一样,它将与我从上一个函数得到的最后一个答案一起工作。 - undefined

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接