gpt4 book ai didi

java - java中带分隔符的2个或多个数字

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:54:14 25 4
gpt4 key购买 nike

我有这个基本程序,在输入个位数时效果很好。但是当计算一个包含多个数字的表达式时,比如 1337 - 456 + 32,程序不会继续......它就像我什么也没做一样。它不会卡住或输出错误消息,它只是停止。

代码如下:

import java.io.*;
import java.util.*;
public class Tester {
public static void main(String args[]) {
Scanner kb = new Scanner(System.in);
System.out.print("Enter number: ");
String s = kb.nextLine();
Scanner sc = new Scanner(s);
//Set delimiters to a plus sign surrounded by any amount of white space...or...
// a minus sign surrounded by any amount of white space.
sc.useDelimiter("\\s*");
int sum = 0;
int temp = 0;
int intbefore = 0;

if (sc.hasNext("\\-")) {
sc.next();
if (sc.hasNextInt()) {
intbefore = sc.nextInt();
int temper = intbefore * 2;
intbefore = intbefore - temper;
}
}
if (sc.hasNextInt()) {
intbefore = sc.nextInt(); //now its at the sign (intbefore = 5)
}
sum = intbefore;

while (sc.hasNext()) {
if(sc.hasNext("\\+")) { //does it have a plus sign?
sc.next(); //if yes, move on (now at the number)
System.out.println("got to the next();");

if(sc.hasNextInt()) { //if there's a number
temp = sc.nextInt();
sum = sum + temp; //add it by the sum (0) and the sum of (5) and (4)
System.out.println("added " + sum);
}
}
if(sc.hasNext("\\-")) {
sc.next();
System.out.println("got to the next();");

if (sc.hasNextInt()) {
temp = sc.nextInt();
sum = sum - temp; //intbefore - temp == 11
System.out.println("intbefore: " + intbefore + " temp: " + temp);
System.out.println("subtracted " + sum); // subtracted by 11
}
}
}
System.out.println("Sum is: " + sum);
}
}

帮助解释为什么会发生这种情况以及如何解决它?(如果有帮助,我正在使用 netbeans)

此外,我假设输入的每个数字之间都有一个空格,例如:123 + -23 - 5

最佳答案

我尝试执行您的代码,这就是我的发现。

假设您的输入是 12+1。

Not sc.hasNextInt() 会给你 1 你要分配给 intbefore

接下来,您代码中的 while 循环将进入无限循环,因为 sc.hasNext() 将始终为真(并在这种情况下返回 2),但它不会' 匹配 while 循环中的两个 if 条件,从而使您的代码在无限循环中运行。现在继续努力。一切顺利。

关于java - java中带分隔符的2个或多个数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14079487/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com