1 回答
TA贡献1757条经验 获得超7个赞
你可以使用这样的东西:
while(scanner.hasNext()) {
//some code
int number = scanner.NextInt();
}
但我会实现一个计算器如下:
int num1 = scanner.NextInt();
String op = scanner.Next();
int num2 = scanner.NextInt();
您可以按如下方式遍历字符串并进行检查:
for (char ch : exampleString.toCharArray()){
System.out.println(ch);
}
您还可以按如下方式循环字符串:
for (int i=0; i<examplestring.length(); i++) {
char c = examplestring.charAt(i);
}
您可以循环直到获得 + 或 - ,如下所示:
char operator;
do {
char operator = scanner.next().get(0);
}while(operator != '+' || operator != '-')
您可以循环和打印错误消息,如下所示:
char operator;
do {
char operator = scanner.next().get(0);
if(!isValidOperator(operator)) {
System.out.println("invalid operator");
}
}while(!isValidOperator(operator))
public boolean isValidOperator(char operator) {
if(operator == '+') {
return true;
} else if (operator == '-') {
return true;
}
return false;
}
添加回答
举报