我是 java 的新手,我正在为 romanCalculator 做这项作业。 我目前正在处理计算部分,但我对请求的某些规则有疑问。
如果输入不正确,则必须打印错误。
所以这是规则之一,这些是唯一可能的输入。
<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} .
最佳答案
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:");
}
关于java - 循环多个扫描仪输入直到特定输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40182896/