Reputation: 13
i needed help displaying the average, smallest and highest number inputted by the user, but i can only display the average and largest numbers. there is another question like this on here but it wasn't exactly solved, giving the smallest number only. if there is a different way other than Math.min and Math.max, that would be greatly appreciated.
import java.text.DecimalFormat;
import java.util.Scanner;
public class ProblemSet3_1 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
DecimalFormat dec = new DecimalFormat();
int snum = 0;
int height = 0;
int add = 0;
double avg = 0;
int largest = 0;
int smallest = 0;
System.out.print("How much students are in your class?" + '\n');
snum = input.nextInt();
for (int i = 1; i <= snum; i++) {
System.out.print("How tall is student #" + i + "?" + '\n');
height = input.nextInt();
add += height;
avg = add / i;
if (height > largest) {
largest = height;
}
}
System.out.print("The average height is " + avg + ", while the tallest is " + largest + " , and the shortest is " + smallest + ".");
}
}
Upvotes: 0
Views: 569
Reputation: 336
Can just add a simple if/else if statement
import java.text.DecimalFormat;
import java.util.Scanner;
public class ProblemSet3_1 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
DecimalFormat dec = new DecimalFormat();
int snum = 0;
int height = 0;
int add = 0;
double avg = 0;
int largest = 0;
int smallest = 0;
System.out.print("How much students are in your class?" + '\n');
snum = input.nextInt();
for (int i = 1; i <= snum; i++) {
System.out.print("How tall is student #" + i + "?" + '\n');
height = input.nextInt();
add += height;
avg = add / i;
if(i == 1) {
smallest = height;
}
else if(height < smallest){
smallest = height;
}
if (height > largest) {
largest = height;
}
}
System.out.print("The average height is " + avg + ", while the tallest is " + largest + " , and the shortest is " + smallest + ".");
}
}
Upvotes: 0
Reputation: 1545
inside for loop, do:
if(i==1){
smallest= height;
largest=height;
}
else {
if(height< smallest)
smallest = height
if(height>largest)
largest = height
}
Upvotes: 1
Reputation: 27946
Yes there's a very simple method using streams:
IntSummaryStatistics stats = IntStream.generate(input::nextInt).limit(snum)
.summaryStatistics();
The stats
object now holds average, count, max, min, sum.
Edit: sorry just realised you want a prompt message as well:
IntStream.rangeClosed(1, snum).map(i -> {
System.out.println("How tall is student " + i + "?");
return input.nextInt();}).summaryStatistics();
Upvotes: 3