有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

if语句表示输入字符串之前的数字总和

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

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

我似乎想不出解决这个问题的办法,如果能在整个问题中提供任何帮助或指导,我将不胜感激,并能真正帮助我理解这样的问题。这是我能做的最好的了

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


共 (1) 个答案

  1. # 1 楼答案

    一种解决方案是根本不使用Scanner#nextInt()方法,而是使用Scanner#nextLine()方法,用String#matches()方法和一个小的Regular Expression(RegEx)值“\d+”确认数值输入。此表达式检查整个字符串是否只包含数字。如果是,则matches()方法返回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),这一点在上面的代码片段中得到了考虑