How to display the highest and lowest numbers input by the user? - java

The program asks the user to input any amount of people they want. The program will then ask for the height of each person (not in feet, just in whole numbers like 5, 7, 10, etc.). The program then displays the average height of all those people as well as the tallest and shortest height out of those people.
The average height part works but my problem is trying to display the tallest height entered and shortest height entered.
package loop2;
import java.io.Reader;
import java.text.DecimalFormat;
import java.util.Random;
import java.util.Scanner;
public class PgmTemplate {
public static void main(String[] args) {
Scanner input =new Scanner(System.in);
int sum =0;
int number=0, n;
int average = 0;
int highest= 0;
int lowest= 0;
lowest = number;
System.out.println("enter the number of people");
n = input.nextInt();
for(int i = 0; i < n; i++) {
System.out.println("enter the height of each person");
number = input.nextInt();
sum += number;
average = sum / n;
}
if(number > highest) {
highest = number;
}else if(number < lowest) {
lowest = number;
}
System.out.println("the average height is "+ average);
System.out.println("the tallest person is " + highest);
System.out.println("the shortest person is " + lowest);
}
}

No need to calculate the average after every input.
I would do it like this:
lowest = Integer.MAX_VALUE
...
for (int i = 0; i < n; i++) {
int number = scanner.nextInt();
sum += number;
if (number > highest)
highest = number;
if (number < lowest)
lowest = number;
}
Then after getting all the input, you have what you need:
System.out.println("the average height is " + (sum / n));
System.out.println("the tallest person is " + highest);
System.out.println("the shortest person is " + lowest);

You need to put those checks between number, highest and lowest inside the loop.
As it stands you're only checking for the latest number that has been input.
Also you don't need to calculate a running average. So, move that outside the loop.
for (int i = 0; i < n; i++) {
System.out.println("enter the height of each person");
number = input.nextInt();
sum += number;
if (number > highest) {
highest = number;
} else if (number < lowest) {
lowest = number;
}
}
average = sum / n;

Related

How to sort an array and display it? [duplicate]

This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 3 years ago.
Here is my code:
package project4;
import java.util.Scanner;
public class ScoreAnalyzer {
//#OfScores is the length of the scores array
public static int numberOfScores = 0;
public static double[] scores = new double[numberOfScores];
public static double sum = 0.0;
public static double place = 0.0;
//Of sorted list
public static double[] sortedList = new double[numberOfScores];
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter the number of scores you'd like to average: ");
numberOfScores = input.nextInt();
scores = new double[numberOfScores];
for (int count = 0; count < scores.length; count++) {
System.out.print("Enter score #" + count + ": ");
place = input.nextDouble();
scores[count] = place;
System.out.println("The score of " + scores[count] + " is " + getGrade(count));
}
sumOfScores();
System.out.println("The average of these scores is: " + averageOfScores());
sort();
System.out.println("The sorted list of scores (above average scores are "
+ "marked with an\n" + "asterisk '*'): " + sortedList[numberOfScores]);
}
public static char getGrade(int i) {
//this
if (scores[i] >= 90.0) {
return 'A';
}
if (scores[i] >= 80.0) {
return 'B';
}
if (scores[i] >= 70.0) {
return 'C';
}
if (scores[i] >= 60.0) {
return 'D';
}
else {
return 'F';
}
}
public static double sumOfScores() {
//sum = 0.0;
for (int i = 0; i < numberOfScores; i++) {
sum += scores[i];
}
return sum;
}
public static double averageOfScores() {
double average = sum / numberOfScores;
return average;
}
public static void sort() {
for (int i = 0; i < scores.length - 1; i++) {
// Find the minimum in the list[i..list.length-1]
double currentMin = scores[i];
int currentMinIndex;
currentMinIndex = i;
for (int j = i + 1; j < scores.length; j++) {
if (currentMin > scores[j]) {
currentMin = scores[j];
currentMinIndex = j;
}
}
// Swap list[i] with list[currentMinIndex] if necessary;
if (currentMinIndex != i) {
sortedList[currentMinIndex] = scores[i];
scores[i] = currentMin;
}
}
}
}
The program's purpose is to prompt the user for the number of scores to be entered first, then allow the user to enter that number of scores. As each score is entered, the program should give them a grade for each score inputted. The program then should use a method to find the sum, pass that sum into a method that finds the average, and sort the array in a method.The sorted array should be displayed along with the average and each score which is above the average should be noted with an asterisk beside it.
When I run the program, I am able to enter the number of scores I want to average, input those scores, obtain the sum and average but I'm having problem sorting it to have the asterisk to above average numbers:
Enter the number of scores you'd like to average: 3
Enter score #0: 90
The score of 90.0 is A
Enter score #1: 80
The score of 80.0 is B
Enter score #2: 70
The score of 70.0 is C
The average of these scores is: 80.0
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 2
at project4.ScoreAnalyzer.sort(ScoreAnalyzer.java:86)
at project4.ScoreAnalyzer.main(ScoreAnalyzer.java:32)
There is a problem with the terminating condition of your for loop. Since the array index starts with 0, the highest index will go up to 2 for an array of size 3. However, count, using which you are accessing elements of scores[], is going up to 3 in your for loop and that is the reason for the ArrayOutOfBoundsException. Change the for loop as follows:
for (int count = 0; count < scores.length ; count++)

Basic Java, Largest and smallest integer

The purpose for the code is to prompt the user for 10 integers and then display the largest and smallest integer. I was able to ask the user for the 10 integers and display the largest number; however, the smallest number isn't shown. I believe the issue is with me setting smallest to 0.
import java.util.Scanner;
public class LargeSmall {
public static void main(String[] args) {
int counter = 1;
int largest = 0;
int smallest = 0;
int number = 0;
Scanner input= new Scanner(System.in);
while (counter <= 10) {
System.out.print("Enter number: ");
number = input.nextInt();
if (number > largest) {
largest = number;
}else if(number < smallest) {
smallest = number;
}else {
System.out.print("Number isn't distinct");
counter = counter + 1;
}
System.out.println("Largest number is: " + largest);
System.out.println("Smallest number is: " + smallest);
}
}
Initialize your values like this so we guarantee that we start with the smallest/largest possible reference for our numbers to compare against to:
int largest = Integer.MIN_VALUE;
int smallest = Integer.MAX_VALUE;
int number;
int old = Integer.MIN_VALUE;
...and then some tweaks have to be made:
Change the way you check for dupe numbers (use and old variable).
Check if every new number is smaller than smallest number always (so, in the first iteration we assign the first value to smallest and largest)
Like this:
number = input.nextInt();
if (old != number) {
old = number;
if (number > largest) {
largest = number;
}
if(number < smallest) {
smallest = number;
}
/* consider moving next line here (this will guarantee to go to the next
iteration only if the numbers are different, and get in the final messages,
valid values for `smallest` and `largest` */
// counter = counter + 1;
} else {
System.out.print("Number isn't distinct");
}
Just make > into >= and < into `<=
Since 0 < 0 evaluates to false, your code block does not run. Thus the correction.
Variable smallest is always 0 so the program never go into this block else if(number < smallest)
You should add this code before if(number < smallest)
if(smallest == 0) {
smallest = number;
}
Also your code doesn't catch the distinct numbers. To find the distinct number you should define a list List<Integer> numbers = null; at the start of the program.
Then you can check if the input is entered or not in the while loop like this:
if(numbers.contains(number))
System.out.print("Number isn't distinct");
else
numbers.add(number);
Sets the largest and smallert variables with the user's first input and then compare
import java.util.Scanner;
public class LargeSmall {
public static void main(String[] args) {
System.out.print("Enter number: ");
Scanner input= new Scanner(System.in);
int number = input.nextInt();
int counter = 1;
int largest = number;
int smallest = number;
while (counter < 10) {
System.out.print("Enter number: ");
number = input.nextInt();
if (number > largest) {
largest = number;
}else if(number < smallest) {
smallest = number;
}else
System.out.print("Number isn't distinct");
counter = counter + 1;
}
System.out.println("Largest number is: " + largest);
System.out.println("Smallest number is: " + smallest);
}
}

Calculating the min and max and deleting them

so for my project this is what i need to do In the sport of diving, seven judges award a score between 0 and 10 where each score may be a floating-point value. The highest and lowest scores are thrown out and the remaining scores are added together. The sum is then multiplied by the degree of difficulty for that dive. The degree of difficulty ranges from 1.2 to 4.8 points. The total is then multiplied by 0.6 to determine the diver’s score.
Write a program that prompts the user for the degree of difficulty and seven judges’ scores and outputs the overall score for that dive. The program should use an array to store the seven scores. The program should also ensure that all inputs are within the allowable data ranges.
Sample output:
Enter the degree of difficulty for the dive (1.2 - 4.8): 7.3
Invalid difficulty. Please re-enter: 1.5
Enter the score for each judge (0.0 - 10.0):
Enter score for judge 1 : 12.3
Invalid score. Please re-enter: 14.5
Invalid score. Please re-enter: 8
Enter score for judge 2 : 7.5
Enter score for judge 3 : 8.5
Enter score for judge 4 : 8
Enter score for judge 5 : 7
Enter score for judge 6 : 8
Enter score for judge 7 : 7.5
Score for the dive is 35.1
What I am stuck on is how to get a code that will automatically take out the min and max...
import java.util.Random;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Random rng = new Random();
int[] values = new int[1000];
// Fill it up
for (int i = 0; i < values.length; i++) {
values[i] = rng.nextInt(100);
}
// Find min
/*int indexOfMin = 0;
int indexOfMax = 0;
for (int i = 0; i < values.length; i++) {
if(values[i] < values[indexOfMin]) {
indexOfMin = i;
}
if (values[i] > values[indexOfMax]) {
indexOfMax = i;
}
}
System.out.println("Minimum is at index " + indexOfMin + " with value " + values[indexOfMin]);
System.out.println("Maximum is at index " + indexOfMax + " with value " + values[indexOfMax]);
*/
double[] difficulty = new double[1];
Scanner keyboard = new Scanner(System.in);
for (int d = 0; d < difficulty.length; d++) {
System.out.println(" Enter Difficulty " + d + ":" );
difficulty[d] = keyboard.nextDouble();
while (difficulty[d] < 1.2 || difficulty[d] > 4.8) {
System.out.println(" Bad value. Try again: ");;
difficulty[d] = keyboard.nextDouble();
}
Scanner keyboard1 = new Scanner(System.in);
double[] scores = new double[7];
for (int i = 0; i < scores.length; i++) {
System.out.println(" Enter score " + i + ":" );
scores[i] = keyboard1.nextDouble();
while (scores[i] < 0.0 || scores[i] > 10.0) {
System.out.println(" Bad value. Try again: ");;
scores[i] = keyboard1.nextDouble();
}
}
}
}
}
and the indecOfMin and indexOfMax are // out of the code because I think i have it wrong or that it doesnt apply/help with this project
Instead of searching for the min or max, you can sort the array of values, and then pull the max off of one end of the array, and the min off of the other end.
For the sorting, you can use a bubble sort:
public double[] bubbleSort(double[] array) {
int numberOfItems = array.length;
for (int pass=1; pass != numberOfItems; pass++) {
for (int index=0; index != numberOfItems-pass; index++) {
if (array[index] < array[index+1]) {
temp = array[index];
array[index] = array[index+1];
array[index+1] = temp;
}
}
}
return array;
}
That will sort the array from least to greatest, and return it.
Then you can pull from the array like this:
int maxIndex = array.length - 1;
double max = array[maxIndex];
double min = array[0];
You may have to make some minor changes to implement it into your own code.

Java - print user input of 4 integers, and the lowest, highest and average number

This program is supposed to take user input of four grades, take these grades and calculate the lowest, highest and average of them. Then it needs to print out the four grades along with the lowest, highest, and average of them with proper labels. I cannot figure out how to print out the four grades with my code, and for some reason it prints out the lowest, highest and average after every iteration of the loop, or every user input.
Here is what I have so far:
public class Test2 {
double total = 0.0;
double max = 0.0;
double min = Double.MAX_VALUE;
public void Test2 (double[] grades){
//Loop through all of the grades.
for(int i = 0; i < 4; i++){
double grade = grades[i];
//Add the grade to the total
total += grade;
//If this is the highest grade we've encountered, set as the max.
if(max < grade){
max = grade;
}
//If this is the lowest grade we've encountered, set as min.
if(min > grade){
min = grade;
}
}
System.out.println("Average is: " + (total / 4));
System.out.println("Max is: " + max);
System.out.println("Min is: " + min); }
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
double[] grades = new double[4];
System.out.println("Please enter number");
for (int i = 0; i < grades.length; i++) {
grades[i] = input.nextDouble();
Test2 g = new Test2();
g.Test2(grades);
} } }
Can anyone help me with this? I need it to print out the four grades (user input), along withe the lowest, highest and average grade from the four grades, but ONLY ONCE, not after every iteration of the loop. Sorry if my code looks bad.
You have to call the method Test2(double grade) only once in the main method as there is a for loop inside Test2 method. I.e call Test2 method in main outside for loop.
Your answer should be the below class.
import java.util.Scanner;
public class Test2 {
double total = 0.0;
double max = 0.0;
double min = Double.MAX_VALUE;
public void doOperations(double[] grades) {
for (int i = 0; i < 4; i++) {
double grade = grades[i];
//Add the grade to the total
total += grade;
//If this is the highest grade we've encountered, set as the max.
if (max < grade) {
max = grade;
}
//If this is the lowest grade we've encountered, set as min.
if (min > grade) {
min = grade;
}
}
System.out.println("Average is: " + (total / 4));
System.out.println("Max is: " + max);
System.out.println("Min is: " + min);
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
double[] grades = new double[4];
System.out.println("Please enter number");
for (int i = 0; i < grades.length; i++) {
grades[i] = input.nextDouble();
}
Test2 test2 = new Test2();
test2.doOperations(grades);
}
}

Java-Number of scores needs to be one less in answer

So here is my code:
package e7;
import java.util.Scanner;
public class Q1 {
public static void main(String[] args)
{
double[] scores = new double[10];
double sum = 0.0D;
int count = 0;
Scanner sc = new Scanner(System.in);
do {
System.out.print("Enter a new score (-1 to end): ");
scores[count] = sc.nextDouble();
if (scores[count] >= 0.0D)
sum += scores[count];
}
while (scores[(count++)] >= 0.0D);
System.out.println("The total number of scores is: " + count );
double average = sum / (count - 1);
int numOfAbove = 0;
int numOfBelow = 0;
for (int i = 0; i < count - 1; i++) {
if (scores[i] >= average)
numOfAbove++;
else
numOfBelow++;
}
System.out.printf("Average is " + "%.2f\n",average);
System.out.println("Number of scores above or equal to the average " + numOfAbove);
System.out.println("Number of scores below the average " + numOfBelow);
}
}
How do make it display the correct number of scores calculated? If I input 2 numbers and then do the -1 one to end it keeps saying 3 scores. Should only be two. How do I fix this? Thanks
System.out.println("The total number of scores is: " + count );
You probably want:
System.out.println("The total number of scores is: " + (count - 1));
You could also change your loop from a do while to a while loop as follows,
while (true) {
System.out.print("Enter a new score (-1 to end): ");
double tempDouble = sc.nextDouble();
if (tempDouble >= 0.0D)
scores[count] = tempDouble;
sum += scores[count];
count++;
else
break;
}
That way as if your double input isn't correct it would break out of the while loop when the user entered -1. You might have to tweak it a bit for your use case.

Categories