Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Your input1 and input2 being added in directly kind of defect the purpose of quitting on the first entered negative number, but the code I displayed below works. It will only prompt the user for any additional numbers if the number entered is non-negative, and it will only sum the entered number if the number is non-negative.</p> <pre><code>package stackoverflow.answers; import java.util.Scanner; public class Total { public static void main(String[] args) { int total = 0, input = 0; /* Print out your "request" for an integer * so the user knows to enter something. */ System.out.print("Enter an integer: "); /* Create a Scanner on the System.in stream */ Scanner entry = new Scanner(System.in); /* Loop while the entered number is &gt; 0 */ while ((input = entry.nextInt()) &gt; 0) { /* If the input &gt; 0, add it to total */ total += input; /* Print out the request again. */ System.out.print("Total: " + total + "\nEnter an integer: "); } /* Just for kicks, print out the total * (only useful if the first entered number * is negative and the total would be 0). */ System.out.println("Total: " + total); } } </code></pre> <p>If you want to sum the negative number, and THEN quit, I suggest changing the while loop to a do-while loop, like this:</p> <pre><code> /* Get an integer and add it to the sum, and * then loop while the entered number is &gt; 0 */ do { /* Get the integer */ input = entry.nextInt(); /* If the input &gt; 0, add it to total */ total += input; /* Print out the request again. */ System.out.print("Total: " + total + "\nEnter an integer: "); } while (input &gt; 0); </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload