【问题标题】:Java Sum of numbers until string is entered输入字符串之前的 Java 数字总和
【发布时间】:2020-04-24 17:05:35
【问题描述】:

我刚刚开始 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

【问题讨论】:

    标签: java if-statement while-loop sum


    【解决方案1】:

    一种解决方案是根本不使用Scanner#nextInt() 方法,而是使用Scanner#nextLine() 方法并使用String#matches() 方法以及一个小的Regular Expression (RegEx) 来确认数字条目的输入“\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)与unsigned 20相同,上面的代码sn-p考虑了这一点。

    【讨论】:

    • 非常感谢您,这确实有助于理解问题。除了负数外,它工作得很好。如果我想在总和中包含负数,我不知道它为什么会这样做,但是当 i -10 为第一个数字时,它会返回一个空的新行。那是因为总和线是正数还是相等?这样一个负 int 返回一个空值?任何清理都会很棒,非常感谢您的帮助:) @DevilsHnd
    • @utnicho - 我明白了...将else if (val.matches("\\d+")) { 更改为:else if (val.matches("\\-?\\d+")) {。这意味着提供的值可能会或可能不会签名。
    【解决方案2】:

    这样做:

    public static void main(String[] args) throws Exception {
        int sum = 0;
        Scanner scan = new Scanner(System.in);
    
        while (scan.hasNext()) {
            System.out.print("Enter a number: ");
    
            if (scan.hasNextInt())
                sum += scan.nextInt();
            else
                break;
    
    
            System.out.println("Sum is now: " + sum);
        }
    
        System.out.print("END");
    }
    

    如果输入不是数字 (int),这将结束。

    正如 cmets 中所指出的,如果您希望程序在用户专门输入“END”时停止,请将 else-statement 更改为:

    else if (scanner.next().equals("END"))
        break;
    

    【讨论】:

    • 如果程序应该只在用户专门输入“END”时停止,将else改为这个else-if:else if (scan.hasNext() && "END".equals(scan.next())) {
    • 感谢您的加入!
    猜你喜欢
    • 2012-06-15
    • 1970-01-01
    • 2021-02-05
    • 1970-01-01
    • 2022-11-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多