Knowee
Questions
Features
Study Tools

code this in java using patterns: Specification: Read in integers until the user enters -1. If there was at least one integer, show the average value.

Question

Code this in Java using patterns:

Specification: Read in integers until the user enters -1. If there was at least one integer, show the average value.

🧐 Not the exact question you are looking for?Go ask a question

Solution

Sure, here is a simple Java program that reads integers from the user until they enter -1, then calculates and prints the average of the entered numbers.

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int sum = 0;
        int count = 0;
        int input;

        System.out.println("Enter integers. Enter -1 to stop.");

        while (true) {
            input = scanner.nextInt();
            if (input == -1) {
                break;
            }
            sum += input;
            count++;
        }

        if (count > 0) {
            double average = (double) sum / count;
            System.out.println("The average is: " + average);
        } else {
            System.out.println("No integers were entered.");
        }
    }
}

This program works as follows:

  1. It first creates a Scanner object to read the user's input.
  2. It then enters a loop where it reads an integer from the user.
  3. If the user enters -1, it breaks out of the loop.
  4. Otherwise, it adds the entered number to the sum and increments the count of numbers.
  5. After the loop, if at least one number was entered (i.e., count > 0), it calculates the average by dividing the sum by the count and prints it.
  6. If no numbers were entered, it prints a message saying so.

This problem has been solved

Similar Questions

Create a program in Java that will accept two integers. If the sum of the integers is odd, display the higher integer, else, display the lower integer.

Initialize an array/list with five integers. Write a program to find the sumand average of these numbers

evelop a Java program that calculates the average of three floating-pointnumbers and displays a grade based on the average.

Select the correct answerThe average of 10 numbers is 7. If each number is multiplied by 12, then the average of the new set of numbers will be?Options7828419

The mean (average) of 5 consecutive integers is 9. The smallest of these 5 integers is

1/2

Upgrade your grade with Knowee

Get personalized homework help. Review tough concepts in more detail, or go deeper into your topic by exploring other relevant questions.