Java Sum of numbers until string is entered

心已入冬 提交于 2021-01-29 14:33:45

问题


i've just started java programming and was wondering on how to approach or solve this problem i'm faced with.

I have to write a program that asks a user for a number and continually sums the numbers inputted and print the result. This program stops when the user enters "END"

I just can't seem to think of a solution to this problem, any help or guidance throughout this problem would be much appreciated and would really help me understand problems like this. This is the best i could do

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

}   


}
    }   

The output is supposed to look like this:

Enter a number: 5

Sum is now: 5

Enter a number: 10

Sum is now: 15

Enter a number: END


回答1:


One solution would be to not use the Scanner#nextInt() method at all but instead utilize the Scanner#nextLine() method and confirm the entry of the numerical entry with the String#matches() method along with a small Regular Expression (RegEx) of "\d+". This expression checks to see if the entire string contains nothing but numerical digits. If it does then the matches() method returns true otherwise it returns 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: Based on Comment:

Since since an integer can be signed (ie: -20) or unsigned (ie: 20) and the fact that an Integer can be prefixed with a + (ie: +20) which is the same as unsigned 20, the code snippet above takes this into consideration.




回答2:


Do it like this:

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");
}

This will end if the input is not a number (int).

As pointed out in the comments, if you want the program to stop when the user specifically enters "END", change the else-statement to:

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


来源:https://stackoverflow.com/questions/61413651/java-sum-of-numbers-until-string-is-entered

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!