davido
davido

Reputation: 37

Scanner example loop

Values are entered until a 0 is entered. Then the program ends, but before that happens the sum of all values are given if they were Integral numbers.

This is what I have tried so far but I'm stuck.

public class Aufgabe2 {

    public static void main(String[] args) {
        /* TODO: add code here */
        int n;
        int sum = 0;
        boolean exit = true;

        Scanner input = new Scanner(System.in);



        while (true) {

            n = input.nextInt();

            if (n == 0) {
                exit = true;
            } else {
                sum += n;
                System.out.println(sum);

            }
        }
    }
}

Upvotes: 2

Views: 898

Answers (3)

Ravindra babu
Ravindra babu

Reputation: 38950

Working code:

import java.util.*;

public class Aufgabe2 {

    public static void main(String[] args) {
        /* TODO: add code here */
        int n;
        int sum = 0;
        boolean exit = false;
        Scanner input = new Scanner(System.in);
        while (!exit) {
            System.out.println("Enter a number:");
            n = input.nextInt();
            if (n == 0) {
                exit = true;
            } else {
                sum += n;
                System.out.println(sum);
            }
        }
    }
}

Output:

Enter a number:
1
1
Enter a number:
3
4
Enter a number:
6
10
Enter a number:
0

Edit:

You have to change while (true) loop to use boolean variable exit. I have modified the code accordingly and corrected the while loop condition.

Upvotes: 0

Shivam
Shivam

Reputation: 649

Try;

int n;
int sum = 0;
boolean exit = true;

Scanner input = new Scanner(System.in);

while (exit) {
    n = input.nextInt();

    if (n == 0) {
        exit = false;
    }
    else {
        sum += n;
        System.out.println(sum);
    }
}

You have a while(true) which is a continuous loop.

Upvotes: 0

AndyN
AndyN

Reputation: 2105

There is some good doco on Scanner on the oracle website: http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html

Scanner will throw an error in the event that the token you are expecting is not there. I would recommend you check for an integer input.hasNextInt() before you attempt to parse it.

Something like this:

int sum = 0;
boolean exit = true;

Scanner input = new Scanner(System.in);

while (input.hasNextInt()) {

  int n = input.nextInt();

  if (n == 0) {
    break;
  } else {
    sum += n;
  }
}
// Print outside of the loop
System.out.println(sum);

Result of the program

Input:
  1
  2
  3
  0
Output:
  6

Upvotes: 2

Related Questions