0

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

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you so much for this, it's really helped understand the problem. It works perfectly except for negative numbers. If i wanted to include negative numbers in the sum, i dont know why it does this actually, but when i -10 for the first number for example, it returns an empty new line. Is that because the sum line is either plus or equal? so that a negative int returns a null value? any clear up would be great, thanks so much for your help otherwise :) @DevilsHnd
@utnicho - I see...Change else if (val.matches("\\d+")) { to this: else if (val.matches("\\-?\\d+")) {. This means the the value supplied may or may not be signed.
1

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;

2 Comments

If the program should only stop when the user specifically enters "END", change the else to this else-if: else if (scan.hasNext() && "END".equals(scan.next())) {
Thank you for the addition!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.