我正在做练习,我必须从键盘输入一个字符串。该字符串将是简单的算术,例如“2 + 4 + 6 - 8 + 3 - 7”。是的,格式必须是这样的。中间有单个空格。
这个想法是取这个字符串并最终打印出答案。到目前为止,这是我的代码:
public class AddemUp { public static void main(String[] args) { Scanner kb = new Scanner(System.in); System.out.print("Enter something like 8 + 33 + 1345 + 137: "); String s = kb.nextLine(); Scanner sc = new Scanner(s); sc.useDelimiter("\\s*\\+\\s*|\\s*\\-\\s*"); int sum = 0; int theInt; Scanner sc1 = new Scanner(s); sc1.useDelimiter("\\s*\\s*"); String plusOrMinus = sc1.next(); int count = 0; if(s.startsWith("-")) { sum -= sc.nextInt(); } while(sc.hasNextInt()) { theInt = sc.nextInt(); if(count == 0) { sum += theInt; } else if(plusOrMinus.equals("+")) { sum += theInt; } else { sum -= theInt; } sc1.next(); count++; } System.out.println("Sum is: " + sum); } } }
在第25行,“sc1.delimiter”所在的位置,我不知道如何让代码跳过所有整数(以及空格)并仅隔离“+”或“ - ”。一旦实现这一点,我可以简单地将其实现到while循环中。
答案 0 :(得分:4)
如果你想消除这些数字,留下一系列操作数,分成其他而不是加号或减号:
String[] ops = str.split("[^+-]+");
fyi,当一个减号在字符类中是第一个或最后一个时它是一个字面减去(否则它是一个范围)
答案 1 :(得分:2)
答案 2 :(得分:1)
您可以使用以下代码
"8 + 33 + 1345 + 137".split("(\\s\\d*\\s)|(\\s\\d*)|(\\d*\\s)")
此处,正则表达式会检查字符串中的数字以及它之前/之后/周围的空格。
此拆分将返回数组 [,+,+,+]
除非字符串以+/-开头,否则首位始终为空,您可以从[1]位置访问数组
答案 3 :(得分:0)
我不会为此使用Scanner,而会使用模式匹配。它们的相反之处在于,扫描程序需要在所需字符之间定界符,而模式匹配则改为标识所需字符。
要查找操作员,您可以拥有此...
Pattern p = Pattern.compile("[+-]");
Matcher m = p.matcher("2 + 4 + 6 - 8 + 3 - 7");
while (m.find()) {
String token = m.group(0);
System.out.println(token);
}
当数字和运算符在一起循环时,逻辑可以直接处理。这就是为什么要包括这个。
Pattern p = Pattern.compile("([^\\s]+)(?:\\s+|$)");
Matcher m = p.matcher("2 + 4 + 6 - 8 + 3 - 7");
while (m.find()) {
String token = m.group(1);
System.out.println(token);
}
these instructions是测试正则表达式的好网站。
答案 4 :(得分:-1)
请改为尝试:
String str = ...
int total = 0;
int operand;
for(int i = 0; i < str.length(); i++){
if(Character.isWhiteSpace(str.charAt(i)))
; // empty
else if(Character.isDigit(str.charAt(i))){
StringBuilder number = new StringBuilder();
while(Character.isDigit(str.charAt(i))){
number.append(str.charAt(i));
i++;
}
operand = Integer.parseInt(number.toString);
}
else if(str.charAt(i)) == '+')
total += operand;
else if(str.charAt(i)) == '-)
total -= operand;
else
throw new IllegalArgumentException();
}
当然,你应该做一个更好的检查,非法入场。我刚刚给了你这个想法。
答案 5 :(得分:-2)
int total = 0;
final String s = "9 - 15";
final String[] arr = s.split(" ");
int i = 0;
while (i != arr.length)
{
switch (arr[i])
{
case ("+"):
total += Integer.parseInt(arr[++i]);
break;
case ("-"):
total -= Integer.parseInt(arr[++i]);
break;
case ("*"):
total *= Integer.parseInt(arr[++i]);
break;
case ("/"):
total /= Integer.parseInt(arr[++i]);
break;
default:
total = Integer.parseInt(arr[i++]);
}
if (i == arr.length - 1)
{
break;
}
}
System.out.println(total);
希望这可以帮助你...... thnx
答案 6 :(得分:-2)
你走了,希望这有帮助...
您即将看到的代码可以解决所有基本方程,这意味着它可以解决仅包含required init?(coder aDecoder: NSCoder) {
self.money = (aDecoder.decodeDouble(forKey: DMED.money.rawValue))
self.netWorth = (aDecoder.decodeDouble(forKey: DMED.netWorth.rawValue))
self.businessNum = (aDecoder.decodeInteger(forKey: DMED.businessNum.rawValue))
self.generalEPM = (aDecoder.decodeInteger(forKey: DMED.generalEPM.rawValue))
self.generalThreat = (aDecoder.decodeInteger(forKey: DMED.generalThreat.rawValue))
}
,.
,+
的方程式等式中的-
和/或*
符号。此等式还可以添加,减去,多个和/或除以小数。此无法解决包含/
,x^y
,(x)
等的公式。
[x]
这是一个例子:
<强>输入:强>
public static boolean isNum(String e) {
String[] num=new String[] {"1", "2", "3", "4", "5", "6", "7", "8", "9", "0"};
boolean ret=false;
for (String n : num) {
if (e.contains(n)) {
ret=true;
break;
}
}
return ret;
}
public static boolean ifMax(String[] e, int i) {
boolean ret=false;
if (i == (e.length - 1)) {
ret=true;
}
return ret;
}
public static String getResult(String equation) {
String[] e=equation.split(" ");
String[] sign=new String[] {"+", "-", "*", "/"};
double answer=Double.parseDouble(e[0]);
for (int i=1; i<e.length; i++) {
if (isNum(e[i]) != true) {
if (e[i].equals(sign[0])) {
double cc=0;
if (ifMax(e, i) == false) {
cc=Double.parseDouble(e[i+1]);
}
answer=answer+(cc);
} else if (e[i].equals(sign[1])) {
double cc=0;
if (ifMax(e, i) == false) {
cc=Double.parseDouble(e[i+1]);
}
answer=answer-(cc);
} else if (e[i].equals(sign[2])) {
if (ifMax(e, i) == false) {
answer=answer*(Double.parseDouble(e[i+1]));
}
} else if (e[i].equals(sign[3])) {
if (ifMax(e, i) == false) {
answer=answer/(Double.parseDouble(e[i+1]));
}
}
}
}
return equation+" = "+answer;
}
<强>输出:强>
System.out.println(getResult("1 + 2 + 3 + 4 / 2 - 3 * 6"));