-4

What i am trying to do is use a while loop to check if int number is positive or negative and depending if such number is positive or negative execute the relevant code. The user is going to keep putting in numbers until they enter a negative number and once they do that the while loop will exit and it will print out the average of all the positive numbers before that negative number was typed in. I was trying to get int number to be reassigned each time the user puts in a number.

this is my code:

import java.util.*;

public class Question7{

    public static void main (String [] args){
        int number=0;
        int average=0;
        int counter=0;
        int sum=0;
        Scanner sc = new Scanner(System.in);
        number = sc.nextInt();
        while (number > 0) {
            counter++;
            sum = sum + number;
            average= sum/counter;
        }
        System.out.println("this is the average:" + average);
    }
}
Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
Cathal Brady
  • 117
  • 1
  • 3
  • 10
  • 2
    You have to reprompt and reassign in the loop body so you have the chance of terminating the loop – Andrew Li Sep 04 '16 at 20:43
  • He's not prompting much less "re"-prompting. – Hovercraft Full Of Eels Sep 04 '16 at 20:46
  • @HovercraftFullOfEels But `sc.nextInt()` is prompting for integer is it not? It's just that he needs to reprompt for another value in loop to update `number` – Andrew Li Sep 04 '16 at 20:47
  • Well there is 1 prompt but it occurs only once before entering a possible infinite loop – Aaron Davis Sep 04 '16 at 20:47
  • @AndrewL.: I always consider a prompt where you "prompt" the user for input. In a console program that would mean a print or println statement. There are none, except for a report of the results. To the original poster: do this -- prompt the user for input before accepting it using a `System.out.print(...)` or println statement, and do this **within** the loop as Andrew suggests. – Hovercraft Full Of Eels Sep 04 '16 at 20:49
  • @HovercraftFullOfEels Oh I see. It's not prompting, but taking in the input. It's expecting an integer to come in. – Andrew Li Sep 04 '16 at 20:50

5 Answers5

1

You need to add number = sc.nextInt(); inside the while loop. Otherwise it would be an infinite loop.

Another point you have missed is integer division. Most of the above answers have missed it too. Both your counter variable and sum variable are integers. Therefore the division will also be an integer division.

consider

sum = 17;
counter = 4;

average would be 17/4=4

Therefore average should be a double. And you have to cast either sum or counter to double.

int average = 0;
average = (double)sum/counter;
Malith
  • 685
  • 1
  • 8
  • 14
0

Your while loop keeps going until counter reachs Integer limit. Then your counter will become 0 and an exception will be thrown.

You need to move number = sc.nextInt(); line into while loop. Thus user input will be required in every iteration.

Raptor
  • 187
  • 1
  • 2
  • 11
0

I have modified your code, and it should be this:

int average = 0;
int counter = 0;
int sum = 0;
int number = 0;
Scanner sc = new Scanner(System.in);
number = sc.nextInt();
while (number >= 0)
{
    counter++;
    sum +=number;

    number = sc.nextInt();
}
if (counter == 0)
    counter = 1;
average = sum/counter;
System.out.println("this is the average:" + average);

A basic explanation, step by step:

  1. User enters a number.
  2. If number is less than 0, skip to step 6.
  3. Increment count.
  4. Set sum to previous sum + user input.
  5. Go to step 1.
  6. Print average, which is sum/counter.


Live Example
Arnav Borborah
  • 11,357
  • 8
  • 43
  • 88
  • `if (number < 0) { break; }` I'm sure someone out there is looking for an answer like this to downvote... – The SE I loved is dead Sep 04 '16 at 21:12
  • I think you should considering using a do/while loop instead of a break as it is usually better form/style. – pamcevoy Sep 04 '16 at 21:14
  • 1
    @ArnavBorborah Because it contains a `break` statement in a `while` loop. Such a `break` is almost on par with a `goto` which is considered harmful. – The SE I loved is dead Sep 04 '16 at 21:15
  • ***If, however, the loop is short and to the point, the purpose of the break statement should be obvious.*** - http://stackoverflow.com/a/3926229/6525260. There is nothing wrong with it for a simple loop like this. It is just a trivial program, and there is nothing beyond the loop – Arnav Borborah Sep 04 '16 at 21:18
0

The main issue is that you need to read input inside the loop using number = sc.nextInt(); preferably at the end of the loop.

Other than that, what if the user enters a zero? Break the loop or not? Should the average be a float or double instead of an int? You don't need to compute the average until the end. It is good to tell the user what to input and it's good to close the scanner.

public static void main (String [] args){
    int number = 0;
    int counter = 0;
    int sum = 0;

    // prompt the user
    String promptMsg = "Enter an integer (negative to quit): ";
    System.out.println(promptMsg);

    Scanner sc = new Scanner(System.in);
    number = sc.nextInt();
    while (number >= 0) {
        counter++;
        sum += number;

        // prompt the user to enter the next input
        System.out.println(promptMsg);
        number = sc.nextInt();
    }

    // defer computing average until here
    double average = sum / counter;
    System.out.println("this is the average:" + average);

    // close up when done
    sc.close();
}
pamcevoy
  • 1,136
  • 11
  • 15
-2

Write a program which continuously takes an integer until a negative number is entered by the user.

import java.util.Scanner;

/**
 *
 * @author MR
 */
public class NewTask9 {

    public static void main(String[] args) {

        int sum = 0;
        Scanner sc = new Scanner(System.in);
        while (true) {
            int number = sc.nextInt();
            if (number < 0) {
                break;
            }
            sum = sum + number;

        }
        System.out.println("this is the sum:" + sum);

    }

}

https://www.youtube.com/@codewithmr786

Auryn
  • 1,117
  • 1
  • 13
  • 37