Java 输入字符串之前的数字总和

标签 java if-statement while-loop sum

我刚刚开始 Java 编程,想知道如何处理或解决我面临的这个问题。

我必须编写一个程序,要求用户输入一个数字,并不断对输入的数字求和并打印结果。 当用户输入“END”时该程序停止

我似乎想不出解决这个问题的方法,任何有关这个问题的帮助或指导都将非常感激,并且会真正帮助我理解这样的问题。这是我能做的最好的事情

public static void main(String[] args) {
    Scanner scan = new Scanner(System.in);

while (true) {
    System.out.print("Enter a number: ");
    int x = scan.nextInt();
    System.out.print("Enter a number: ");
    int y = scan.nextInt();

    int sum = x + y;


    System.out.println("Sum is now: " + sum);   

}   


}
    }   

输出应该如下所示:

输入数字:5

现在总和:5

输入数字:10

现在总和:15

输入数字:END

最佳答案

一种解决方案是不使用 Scanner#nextInt()方法,而是利用 Scanner#nextLine()方法并使用 String#matches() 确认数字条目的输入。方法连同一个小Regular Expression (正则表达式)“\d+”。该表达式检查整个字符串是否只包含数字。如果是,则 ma​​tches() 方法返回 true,否则返回 false。

Scanner scan = new Scanner(System.in);
int sum = 0; 
String val = "";
while (val.equals("")) {
    System.out.print("Enter a number (END to quit): ");
    val = scan.nextLine();
    // Was the word 'end' in any letter case supplied?
    if (val.equalsIgnoreCase("end")) {
        // Yes, so break out of loop.
        break;
    }
    // Was a string representation of a 
    // integer numerical value supplied?  
    else if (val.matches("\\-?\\+?\\d+")) {
        // Yes, convert the string to integer and sum it. 
        sum += Integer.parseInt(val);
        System.out.println("Sum is now: " + sum);  // Display Sum
    }
    // No, inform User of Invalid entry
    else {
        System.err.println("Invalid number supplied! Try again...");
    }
    val = "";  // Clear val to continue looping
}

// Broken out of loop with the entry of 'End"
System.out.println("Application ENDED"); 

编辑:基于评论:

因为整数可以是有符号(即:-20)或无符号(即:20),并且整数可以以前缀>+(即:+20)与无符号 20 相同,上面的代码片段考虑了这一点。

关于Java 输入字符串之前的数字总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61413651/

相关文章:

python - 在 Python 中重构长语句

mysql - 循环运行时连续从串口读取数据

c - 程序卡在while循环中

java - 当我已经使用 onBackPressed() 来让 webview 返回时,如何在 android 应用程序中弹出警报框以退出?

java - LibGDX - 无法从 Android Studio 运行 destop 版本

java - 为什么 main() 方法不会抛出形参与实参不匹配的错误?

javascript - 根据值(value)显示特定输入

c++ - 嵌套的 if 语句 C++

java - 如何使用 equals 方法将对象添加到数组列表中以排除相似的对象?

java - 将 LocalDateTime 转换为日期