我有一个名为questions String
类型的数组,存储在问题中。
我想将questionArray[0]
转换为int
。
我使用以下语句来做到这一点。
int aa = Integer.parseInt(questionArray[0]);
但是当我实现这个语句时,当我运行应用程序时,我得到一个错误:invalid int: "10-4"
。
请注意,10-4
可以是任意随机算术表达式,因为它是一个随机问题游戏。例如:9+1
,10/5
等。
答案 0 :(得分:4)
"10-4"
不是一个简单的整数,它是一个计算,因此将其解析为int
将不会产生任何结果..
你必须解析你的字符串..
int aa = evaluteQuestion(questionArray[0]);
实际的魔法发生在这里:
public static int evaluteQuestion(String question) {
Scanner sc = new Scanner(question);
// get the next number from the scanner
int firstValue = Integer.parseInt(sc.findInLine("[0-9]*"));
// get everything which follows and is not a number (might contain white spaces)
String operator = sc.findInLine("[^0-9]*").trim();
int secondValue = Integer.parseInt(sc.findInLine("[0-9]*"));
switch (operator){
case "+":
return firstValue + secondValue;
case "-":
return firstValue - secondValue;
case "/":
return firstValue / secondValue;
case "*":
return firstValue * secondValue;
case "%":
return firstValue % secondValue;
// todo: add additional operators as needed..
default:
throw new RuntimeException("unknown operator: "+operator);
}
}
如果表达式中有更多部分,则可能需要将上面的代码放入循环中。但请注意操作顺序。如果你想为任何表达式实现适当的解析器,事情可能会变得有点毛茸茸
答案 1 :(得分:0)
它比解析String
有点复杂,因为它有一个算术符号,它可以是任何东西。所以,让我们一步一步地讨论它:
//Lets say you have a string like this
questionArray[0] = "10+4";
//Lets find the Arithmetic sign first in the String
String sign = null;
Pattern regex = Pattern.compile("[+*/]|(?<=\\s)-");
Matcher matcher = regex.matcher(questionArray[0]);
while(matcher.find()) {
sign = matcher.group().trim(); //Store that Arithmetic sign here.
}
String [] parts = questionArray[0].split("[+*/]|(?<=\\s)-"); //Now break up the string using this regex.
//This regex will find whatever Arithmetic sign
//there is inside this String and store the result
//in parts array.
int firstNumber = Integer.parseInt(parts[0]); //The first number in the String
int secondNumber = Integer.parseInt(parts[1]);//The second number in the String
//a simple if-else statements that will help us find the final answer.
int result = 0;
if (sign.equals("+")){
result = firstNumber + secondNumber;
} else if (sign.equals("-")) {
result = firstNumber - secondNumber;
} else if(sign.equals("*")) {
result = firstNumber * secondNumber;
} else if (sign.equals("/")){
result = firstNumber / secondNumber;
} else {
System.out.println("unknown operation");
}
System.out.println(result);