3

I'm trying to read in and add up (only) positive integers until a negative integer is entered. The program is supposed to stop only when a negative integer is entered. The best I've been able to come up with is the code below but the problem is it doesn't stop even when a negative integer is read. PS: I'm still learning so please bear with me. I've tried adding && input2!<0 to the while loop condition but it comes up as an error. Any suggestions as to how I can make it behave the way I want it to? Thanks.

public class Total{
    public static void main(String[] args){

            System.out.println("Enter an integer: ");

            Scanner entry = new Scanner(System.in);
            int input1 = entry.nextInt();

            System.out.println("Enter another integer: ");
            int input2 = entry.nextInt();

            int total = input1 + input2;

            while (input2 > 0){            
                System.out.println(total + "\nEnter another interger:  ");
                total += entry.nextInt();
            }
    }
}
Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
Neo
  • 117
  • 2
  • 3
  • 10

8 Answers8

8

You need to change the variable that is being tested, here input2, inside of the loop. Else there's no chance of exiting. All you change in the loop is the total variable while input2 remains unchanged, and so every time it is tested, it remains >0 and that's why you're stuck. Why not give it another try, this time changing input2 (and still changing total as well, using input2), and see if you can't get it.

Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
4

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.

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 > 0 */
        while ((input = entry.nextInt()) > 0) {
            /* If the input > 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);
    }
}

If you want to sum the negative number, and THEN quit, I suggest changing the while loop to a do-while loop, like this:

        /* Get an integer and add it to the sum, and
         * then loop while the entered number is > 0 */
        do {
            /* Get the integer */
            input = entry.nextInt();

            /* If the input > 0, add it to total */
            total += input;

            /* Print out the request again. */
            System.out.print("Total: " + total + "\nEnter an integer: ");
        } while (input > 0);
Pandacoder
  • 708
  • 7
  • 11
2

The number you accept inside the loop is not storing into the input2 variable. So the program will never exit.By the way you don't even need input2. variable input1 is enough. See the sample program below:

public static void main(String[] args){


            System.out.println("Enter an integer: ");

            Scanner entry = new Scanner(System.in);
            int input1 = entry.nextInt();


            int total =input1;

            while (input1 > 0){
                System.out.println(total + "\nEnter another interger:  ");
                input1 = entry.nextInt();
                total += input1;

            }
    }
Prem
  • 329
  • 1
  • 11
  • @Hovercraft Full Of Eels I completely agree. My mistake. wouldn't have given the answer. I didn't saw your answer. Otherwise wouldn't have answered. – Prem Aug 04 '13 at 00:24
0
public class WhileLoopExample {

    public static void main(String[] args) {

        int i=1;
        System.out.println("While Loop Demo");
        while(i<=10){
            System.out.println(i);
            i++;
        }
    }
}
Paul Roub
  • 36,322
  • 27
  • 84
  • 93
Sidarth
  • 69
  • 1
  • 4
  • Excessive promotion of a specific product/resource may be perceived by the community as spam. Take a look at the [help center](http://stackoverflow.com/help), specially [What kind of behavior is expected of users?](http://stackoverflow.com/help/behavior)'s last section: Avoid overt self-promotion. You might also be interested in [How do I advertise on Stack Overflow?](http://stackoverflow.com/help/advertising) – Draken May 26 '16 at 07:46
0
int input1 = entry.nextInt();

        System.out.println("Enter another integer: ");
        int input2 = entry.nextInt();

        int total = input1 + input2;

        while (input2 > 0){            
            System.out.println(total + "\nEnter another interger:  ");
            total += entry.nextInt();

In last line you are directly taking the input without checking its positivity you are directly adding it to total. Also, in while loop your condition is while(input2>0). Suppose your input2 gets a positive value then the while loop will never end. So make the change by replacing the code with below code

int input1 = entry.nextInt();

             if(input1>0)
            int total =input1;

                while (input1 > 0){
                System.out.println(total + "\nEnter another interger:  ");
                input1 = entry.nextInt();
                    if(input1>0)
                total += input1;
               }
Shubham Agrawal
  • 298
  • 4
  • 10
0
while(Boolean_expression) {
   // Statements
}

Boolean_expression like true/false;

// Statements like     System.out.prinln("Jai Shree Ram");
0

Here's a simple change, instead of using a while loop, you could try using a do while loop! I know this is late, but I'm learning along the way and I'm taking this as a practise!

    Scanner scanner = new Scanner(System.in);

    System.out.println("Enter an integer: ");
    int input1 = scanner.nextInt();

    System.out.println("Enter another integer: ");
    int input2 = scanner.nextInt();

    int total = input1 + input2;

    do{
        System.out.println(total + "\nEnter another integer: ");
        input2 = scanner.nextInt();
        total += input2;
    }while(input2 > 0); //leaves when  input is < 0

Based on my understanding, input2 variable has already been assigned a value before the loop even started, hence when you try to input again it'll not work because you did not change your input2 variable. Thanks for the problem!

Bryan Loo
  • 1
  • 1
0

Q1 - Define a scanner object called input, and let the user enter 10 numbers, then do a summation of all the 10 numbers, and print the result of the operation at the end.