Java数字之和,直到输入字符串

问题描述 投票:0回答:1

我刚刚开始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 basic
1个回答
1
投票

一个解决方案是不使用 Scanner#nextInt() 方法,而是利用 Scanner#nextLine() 的方法,并确认数字条目的输入,用 String#matches() 方法和小 正则表达式 (RegEx) "\d+". 这个表达式检查整个字符串是否只包含数字数字。如果是,那么 匹配() 方法返回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"); 

EDIT:根据Comment。

因为一个整数可以是 签署 (即:-20)或 无符号 (即:20),而且一个整数可以在前面加上一个 + (即:+20),这等于说 无符号 20、上面的代码片段考虑到了这一点。


1
投票

像这样做。

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).

正如评论中所指出的,如果你想让程序在用户输入 "END "的时候停止,可以将程序的 else-声明:

else if (scanner.next().equals("END"))
    break;
© www.soinside.com 2019 - 2024. All rights reserved.