我正在做一个练习,我必须从键盘输入一个字符串。该字符串将是简单的算术,例如“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);
}
}
}
在“sc1.delimiter”所在的第 25 行,我不知道如何让代码跳过所有整数(连同空格)并仅隔离“+”或“-”。实现后,我可以简单地将其实现到 while 循环中。
最佳答案
如果你想消除数字,留下一个操作数数组,拆分字符 other 而不是加号或减号:
String[] ops = str.split("[^+-]+");
仅供引用,当减号是字符类中的第一个或最后一个时,它是一个文字减号(否则它是一个范围)
关于java - 我怎样才能 "delimit"来自给定字符串的整数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13851588/