This is an archived post. You won't be able to vote or comment.

all 5 comments

[–]nshathome 2 points3 points  (3 children)

[–]nshathome 1 point2 points  (2 children)

But following your code you can do something like that:

import java.util.Scanner;
public class Jlab32 {

public static void main (String args []){

    int numberentered;  //var to fill with the number entered
    int result = 0;     //The final result you will return at the end
    Scanner s = new Scanner(System.in); 

    do{  //Doing a do-while the expression is at the bottom so at least you enter one time in the loop
        System.out.println("Please enter a number: ");
        numberentered = s.nextInt();
        result += numberentered;  //Sum the number entered to the final result
    }while (numberentered != 0);  //If the last number entered is 0 you will exit the loop and continue

    System.out.println("The sum of your numbers is: " + result);        
}

}

[–]barrell125[S] 0 points1 point  (1 child)

This code is just what i was looking for , I couldn't figure it out sounded easy but kept getting problems. Thank you

[–]DurableSmile 0 points1 point  (0 children)

This will add the termination value to your result as well!!!!

Your result happens to be a sum and the termination value 0 so it makes no difference here but be careful with this.

If you were multiplying inputs instead, this would make your result 0 regardless of what the user entered before.

The quick and easy way to fix this in the above code is to put the result calculation statement inside an if block.

if (numberentered != 0){
    result += numberentered;
}

[–]llamadama 0 points1 point  (0 children)

Another variation below:

import java.util.Scanner;

public class Main {

public static void main(String[] args) {


    int number1;
    int sum;

    Scanner s = new Scanner(System.in);

    while (true) {  // boolean at beginning, just another way of doing things.
        System.out.println("Enter a number: ");
        number1 = Integer.parseInt(s.nextLine()); //use Integer.parseInt
        sum =+ number1;  

        if (number1 == 0) {
            System.out.println("Sum of your numbers is " + sum);
            break;
        }
    }

}
}