Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Write a JAVA program to read in positive integers until a negative value is ente

ID: 3730436 • Letter: W

Question

Write a JAVA program to read in positive integers until a negative value is entered, then it processes the values except for the last negative value and displays the largest value, smallest value, and the average of the entire values.

Ex)

Output:

Please enter a positive integer, or -1 to quit.

Input: 1

Output:

Please enter a positive integer, or -1 to quit.

Input: 2

Output:

Please enter a positive integer, or -1 to quit.

Input: 3

Output:

Please enter a positive integer, or -1 to quit.

Input: 4

Output:

Please enter a positive integer, or -1 to quit.

Input: -1

Output:

For the 4 numbers you entered

the largest value = 4

the smallest value = 1

and the average is = 2.5

Explanation / Answer

import java.io.*;
import java.util.Scanner;
class Main {
public static void main (String str[]) throws IOException {
  
// DECLARING variables
Scanner scan = new Scanner (System.in);
int arr[] = new int [100];
int count = 0;
  
// taking user input
for (int i=0; i< arr.length; i++)
{
System.out.print("Please enter a positive integer, or -1 to quit. Input:");
arr[i] = scan.nextInt();
if (arr[i] < 0)
{
count = i;
break;
}
}

// declaring variables for output
int max = arr[0];
int min = arr[0];
int sum = arr[0];
  
// finding min, max and average
for (int i =1; i<count; i++)
{
if(min > arr[i])
min = arr[i];
if(max < arr[i])
max = arr[i];
sum += arr[i];
}
  
// printing output
System.out.println("For the "+count+" numbers you entered");
System.out.println("the largest value = "+max);
System.out.println("the smallest value = "+min);
System.out.println("and the average is = "+sum/(double)count);
}
}

/* SAMPLE OUTPUT
Please enter a positive integer, or -1 to quit.
Input: 1
Please enter a positive integer, or -1 to quit.
Input: 2
Please enter a positive integer, or -1 to quit.
Input: 3
Please enter a positive integer, or -1 to quit.
Input: 4
Please enter a positive integer, or -1 to quit.
Input: -1
For the 4 numbers you entered
the largest value = 4
the smallest value = 1
and the average is = 2.5
*/