-1

I've been trying to get a hang of this number averaging program, basically, it takes inputs from the user, and once -1 is inputted, it will average all those inputs. I'm struggling to find a way to give the average as it is giving strange answers as of yet.

Here is the code:

import java.util.Scanner;

public class LoopingDemo1 {

    public static void main(String[] args) {
        String input = "";
        int num = 0;
        int sum = 0;
        Scanner in = new Scanner(System.in);
        int z = -1;
        int i = 0;
        int counter = 0;
        counter++;

        while (i <= 0) {
            System.out.println("Please input a number");
            input = in.nextLine();

            num = Integer.parseInt(input);

            if (num == z) {
                int average = sum / counter;
                System.out.println("Average value is: " + average);
            } else {
                sum += num;
            }

            //what does this operator do? sum = sum + num
        }

        counter++;
    }
}

I do apologize in advance if this is breaking any rules.

5
  • you are doing integer division, changes the variables to doubles Jan 3, 2018 at 17:11
  • One of your questions is hidden in the source code. Yes sum += num is a shorthand for sum = sum + num. As for the rest: please create a minimal reproducible example and give concrete expected and observed values.
    – Turing85
    Jan 3, 2018 at 17:11
  • 1
    Define your inputs, and define your "strange answers". What are they. Why are they strange?
    – JB Nizet
    Jan 3, 2018 at 17:11
  • "Strange answers" that you get are totals, not averages, because you increment count outside the loop, and because you do integer division. Jan 3, 2018 at 17:11
  • @dasblinkenlight I was about to say almost the same thing then noticed your answer. I would like to point out, however, that "integer division" is not a problem, it simply rounds the result, rather than returning a decimal and should not hinder the given results enough to matter.
    – Wayne
    Jan 3, 2018 at 17:20

1 Answer 1

0

try this

int counter = 1;
while (true) {

    System.out.println("Please input a number");
    input = in.nextLine();

    num = Integer.parseInt(input);

    if (num == z) {
        double average = (double)sum / counter;
        System.out.println("Average value is: " + average);
        break;
    } else {
        sum += num;
        counter++;
    }

}
1
  • Code-only answer are discouraged. You should explain the problem(s), as well as the changes you made and how they fix the problem(s).
    – Turing85
    Jan 3, 2018 at 17:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.