I have a question which asks me to enter some exam score to find the highest and the lowest score overall. (Highlighted question.)
float sum = 0, score1, score2 = 0, score3 = 0;
do
{
System.out.println("Enter a score [negative score to quit]: ");
Scanner Score1 = new Scanner(System.in);
score1 = Score1.nextFloat();
if (score1>score2)
{
max = score1;
min = score2;
}
else if(score1<score2)
{
max = score2;
min = score1;
}
else{
score3 = score2;
}
}
}
while (score1>=0);
System.out.printf("Minimun Score = %.0f\n", min);
System.out.printf("Maximum Score = %.0f\n", max);
Enter a score [negative score to quit]:
99
Enter a score [negative score to quit]:
1
Enter a score [negative score to quit]:
6
Enter a score [negative score to quit]:
5
Enter a score [negative score to quit]:
-1
Minimum Score = 5
Maximum Score = 6
BUILD SUCCESSFUL (total time: 7 seconds)
The problem is it only compares the latest 2 score that I entered.
How do i fix this?
The do-while logic may not work in the above code. see the working code below..
float sum = 0, score = 0;
float min = 0, max = 0, ave = 0;
Scanner stdInput = new Scanner(System.in);
System.out.println("Enter the scores: ");
min = max = score = stdInput.nextFloat();
do {
System.out.println("Enter a score [negative score to quit]: ");
if (score > max) {
max = score;
}else if (score < min) {
min = score;
}
sum += score;
// Read the input here so that, the code does not process the negative input.
score = stdInput.nextFloat();
} while (score >= 0);
System.out.println(min);
System.out.println(max);
Logic in if-else ladder is incorrect.
You may find following useful:
class Test
{
public static void main (String[] args) throws java.lang.Exception
{
try(Scanner Score1 = new Scanner(System.in))
{
//Marks are in range of 0-100
float curNum, max = -1, min = 101, sum = 0, sumsq = 0;
boolean flg = true;
while(flg)
{
System.out.println("Enter a score [negative score to quit]: ");
curNum = Score1.nextFloat();
if(curNum<0) break;
if(max < curNum) max = curNum;
if(min > curNum) min = curNum;
sum += curNum;
sumsq += (curNum*curNum);
}
System.out.printf("Minimun Score = %.0f\n", min);
System.out.printf("Maximum Score = %.0f\n", max);
}
}
}
You can find it working here
Related
I have this program where the user inputs x amount of grades, then the program divides the sum of the grades by the number of inputs taken. It should also find the highest and lowest grades entered. When the user is finished, he/she types in -1 to end the program. However, I am having some issues with it.
The program adds -1 to the average which skews all my results.
I can't figure out how to calculate the minimum value in the list. It always counts -1 as the minimum value.
Here is the code below:
import java.util.Scanner;
public class Lab4_EnteringGrades
{
public static void main (String a[])
{
Scanner kb = new Scanner(System.in);
double average = 0;
double gradesSum = 0;
int grade = 0;
int numTests = 0;
int maxValue = 0;
int minValue = 0;
while (grade != -1)
{
gradesSum += grade;
numTests += 1;
average = gradesSum / numTests;
System.out.print("Enter a grade: ");
grade = kb.nextInt();
while ((grade < -1) || (grade > 100))
{
System.out.println("Invalid grade.");
System.out.print("Enter a grade: ");
grade = kb.nextInt();
}
if (grade > maxValue)
maxValue = grade;
if (grade < maxValue)
minValue = grade;
}
System.out.printf("\nTotal number of tests: %d", numTests);
System.out.printf("\nThe average is %.1f", average);
System.out.printf("\nThe max value is %d", maxValue);
System.out.printf("\nThe min value is %d", minValue);
}
}
I made few changes -
Initialization of minValue and maxValue , in your original code, minValue was -1 and grade could not be less than -1, hence you always saw minValue as -1.
In general, if you want min and max vales, it is better to initialize like I did here.
Moved the logic of calculating grade, average AFTER user has entered the grade in order not to mess up the average.
Your original code was:
if (grade < maxValue)
I changed this to be if (grade < minValue). I believe it was a typo.
import java.util.Scanner;
public class Lab4_EnteringGrades {
public static void main (String a[])
{
Scanner kb = new Scanner(System.in);
double average = 0;
double gradesSum = 0;
int grade = 0;
int numTests = 0;
int maxValue = Integer.MIN_VALUE;
int minValue = Integer.MAX_VALUE;
while (true)
{
System.out.print("Enter a grade: ");
grade = kb.nextInt();
while ((grade < -1) || (grade > 100))
{
System.out.println("Invalid grade.");
System.out.print("Enter a grade: ");
grade = kb.nextInt();
}
if (grade == -1) {
break;
}
gradesSum += grade;
numTests += 1;
average = gradesSum / numTests;
if (grade > maxValue)
maxValue = grade;
if (grade < minValue)
minValue = grade;
}
System.out.printf("\nTotal number of tests: %d", numTests);
System.out.printf("\nThe average is %.1f", average);
System.out.printf("\nThe max value is %d", maxValue);
System.out.printf("\nThe min value is %d", minValue);
} }
The problems are that
You do gradesSum += grade; before reading the first grade, when grade is still 0.
You do if (grade < maxValue) after the user has entered grade=-1;, thus always find that -1 is smaller.
You compare the grade to maxValue both for checking max and min
Since you initialize minValue=0, you won't ever find a smaller value (except -1), so you should initialize it to something larger
You can move all the code that processes the grade until after you've read it, and then break if the user enters -1:
import java.util.Scanner;
public class Lab4_EnteringGrades
{
public static void main (String a[])
{
Scanner kb = new Scanner(System.in);
double average = 0;
double gradesSum = 0;
int grade = 0;
int numTests = 0;
int maxValue = 0;
int minValue = 101;
while (true)
{
System.out.print("Enter a grade: ");
grade = kb.nextInt();
while ((grade < -1) || (grade > 100))
{
System.out.println("Invalid grade.");
System.out.print("Enter a grade: ");
grade = kb.nextInt();
}
// Stop if the user entered -1
if (grade == -1) break;
gradesSum += grade;
numTests += 1;
average = gradesSum / numTests;
if (grade > maxValue)
maxValue = grade;
if (grade < minValue)
minValue = grade;
}
System.out.printf("\nTotal number of tests: %d", numTests);
System.out.printf("\nThe average is %.1f", average);
System.out.printf("\nThe max value is %d", maxValue);
System.out.printf("\nThe min value is %d", minValue);
}
}
The while(true) { if(..) break; } is slightly awkward though. You can improve the code further by creating a separate function for reading input:
import java.util.Scanner;
public class Lab4_EnteringGrades
{
public static int readGrade(Scanner kb) {
System.out.print("Enter a grade: ");
int grade = kb.nextInt();
while ((grade < -1) || (grade > 100))
{
System.out.println("Invalid grade.");
System.out.print("Enter a grade: ");
grade = kb.nextInt();
}
return grade;
}
public static void main (String a[])
{
Scanner kb = new Scanner(System.in);
double average;
double gradesSum = 0;
int grade;
int numTests = 0;
int maxValue = Integer.MIN_VALUE;
int minValue = Integer.MAX_VALUE;
// Common idiom for reading a grade until it's -1
while ((grade = readGrade(kb)) != -1) {
gradesSum += grade;
numTests += 1;
if (grade > maxValue)
maxValue = grade;
if (grade < minValue)
minValue = grade;
}
// Consider handling the case of numTests == 0
average = gradesSum / numTests;
System.out.printf("\nTotal number of tests: %d", numTests);
System.out.printf("\nThe average is %.1f", average);
System.out.printf("\nThe max value is %d", maxValue);
System.out.printf("\nThe min value is %d", minValue);
}
}
The first part of the exercise was to calculate the test score average. The next problem asked me to build off this problem and calculate the minimum and maximum. Can anyone help me? This is my code so far.
import java.util.Scanner;
import java.io.*;
import java.text.DecimalFormat;
public class hw
{
public static void main ( String[] args )
{
int maxGrade;
int minGrade;
int count=0;
int total=0;
final int SENTINEL = -1;
int score;
Scanner scan = new Scanner( System.in);
System.out.println( "To calculate the class average, enter each test
score.");
System.out.println( "When you are finished, enter a -1.");
System.out.print( "Enter the first test score > ");
score = scan.nextInt();
while (score != SENTINEL )
{
total += score;
count ++;
System.out.print("Enter the next test score > ");
score = scan.nextInt();
}
if (count != 0)
{
DecimalFormat oneDecimalPlace = new DecimalFormat("0.0");
System.out.println( "\nThe class average is "
+ oneDecimalPlace.format( (double) (total) / count ));
}
else
System.out.println("\nNo grades were entered");
}
}
in your while loop, you can compare the current score to the maximum and the minimum.
while (score != SENTINEL )
{
total += score;
count ++;
if(score > maxGrade)
maxGrade = score;
if(score < minGrade)
minGrade = score;
System.out.print("Enter the next test score > ");
score = scan.nextInt();
}
You also need to set the max and min (when declaring them) to their "opposite" value:
int maxGrade = Integer.MIN_VALUE;
int minGrade = Integer.MAX_VALUE;
Hi i am having trouble with loops. I am confused on how to set up a way to get the
the lowest score
the highest score
the average of the scores
and If no scores were entered, display the message that “No test grade scores were entered”.
i also had to sent up a counter which i did, and i also had to validate if the score was from 0 to 100 which i did i just don't know what to do next
import java.util.Scanner;
public class loops {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int average = 0;
int count = 0;
int score;
System.out.print("Please enter first score:");
score = keyboard.nextInt();
while (score!=-1){
while ((score>=0)&&(score<=100)){
System.out.println("the score is between 0 to 100 ");
System.out.println("Please enter the next test score:");
score = keyboard.nextInt();
count = count + 1;
}
}
average = (score/count);
System.out.println("The average is " +average);
System.out.println("The number of test scores enter was:"+count);
}
}
See explanations in comments:
import java.util.Scanner;
public class Loops { //use java naming convention
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int count = 0, score = 0, min = 0, max = 0, sum =0;
float average = 0;//the average might not be int
System.out.print("Please enter first score:");
score = keyboard.nextInt();
//add it to sum
sum = score;
//keep first number as min and max
min = score; max = score;
count++;//increment counter
//this is not needed, score of -1 will stop the next loop any way
//while (score!=-1){
while (true){
System.out.println("the score is between 0 to 100 ");
System.out.println("Please enter the next test score, or -1 to quit:");
score = keyboard.nextInt();
if((score < 0) ||(score > 100)) {
break;
}
count++;//increment counter
//you need to sum all entered numbers
sum += score;
//check if entered number is min
if(score < min) {
min = score ;
}
//check if entered number is max
if(score > max) {
max = score ;
}
}
if(count >0 ) {
average = ((float)sum/count);
System.out.println("The average is " +average );
System.out.println("The min is " +min);
System.out.println("The max is " +max);
System.out.println("The number of test scores enter was:"+count);
}else {
System.err.println("No numbers entered");
}
}
}
Don't hesitate to ask for clarifications as needed.
I have a java program that takes the scores of 4 players and computes each player's average score when -1 is inputted. At the end of the program I need to display the highest average score out of the 4 averages, however I cannot figure out how to do this, can you guys set me in the right direction? The program looks like this when it is run: (I have also attached my code) I cannot use anything but loops.
Player 1
Enter your score: 100
Enter your score: 90
Enter your score: 80
Enter your score: 70
Enter your score: -1 (when -1 is inputted, the average score is calculated)
Average Score = 85.00
Player 2
Enter your score: 90
Enter your score: 90
etc.
etc.
import java.util.Scanner;
public class BowlingScores
{
public static void main(String[]args)
{
double score = 0;
double totalScore = 0;
double count = 0;
Scanner input = new Scanner(System.in);
for (int player = 1; player <= 4; player++){
System.out.printf("\nPlayer %d\n", player);
do{
System.out.println("Enter Your Score: ");
totalScore = totalScore + score;
score = input.nextDouble();
count++;
} while (score != -1);
if (score == -1){
count--;
System.out.printf("Average Score = %.2f\n",totalScore/count);
count = 0;
score = 0;
totalScore = 0;
}
}
}
}
Just keep track of the highest average in another variable. Then in your score == -1 condition check to see if the current average is higher than the highest average, and if so make current the new highest. Then after your for loop you could print out the highest average.
You can add a copy of the highest at the top of your code like this double highest = 0 then in your for loop have a way to replace it if the current average is higher.
if(score > highest){
highest=score;
}
Then at the -1 you can either reset it to 0 or keep it going.
public static void main(String[] args) {
final List<Double> allAverages = new ArrayList<>();
double score = 0;
double totalScore = 0;
double avg = 0;
int count = -1;
Scanner input = new Scanner(System.in);
for (int player = 1; player <= 4; player++) {
System.out.printf("\nPlayer %d\n", player);
do {
System.out.println("Enter Your Score: ");
totalScore = totalScore + score;
score = input.nextDouble();
count++;
} while (score != -1);
avg = totalScore / count;
System.out.printf("Average Score = %.2f\n", avg);
allAverages.add(totalScore / count);
score = 0;
totalScore = 0;
count = -1;
}
System.out.println("The highest is : " + Collections.max(allAverages));
}
Here a list of the modifications I did to your code to get it working :
The variable count now start at -1, so there is no need to do count-- when we exit the loop.
I've added a List that keep a track of all the averages.
I've removed the validation if(count == -1) after the loop as the only way to exit the loop is to have count == -1 so we already know it is the actual value.
To retrieve the maximum of all averages, I use Collections.max(allAverages).
Take average of all 4 players and store into one array. Then check for the largest number in array.
double[] highest = new double[4];
for(int i=0; i<4; i++){
highest[i] = totalScore/count;
}
if(highest[0]>highest[1] && highest[0]>highest[2] && highest[0]>highest[3])
System.out.println("highest" + highest[0]);
else if(highest[1]>highest[0] && highest[1]>highest[2] && highest[0]>highest[3])
System.out.println("highest" + highest[1]);
else if(highest[2]>highest[0] && highest[2]>highest[1] && highest[0]>highest[3])
System.out.println("highest" + highest[2]);
else System.out.println("highest" + highest[3]);
public static void main(String[]args) {
double bestScore = 0;
int bestPlayer = 1;
Scanner input = new Scanner(System.in);
for (int player = 1; player <= 4; player++){
System.out.printf("\nPlayer %d\n", player);
int count = 0; // does not need to be double
double totalScore = 0;
do {
System.out.println("Enter Your Score: ");
double score = input.nextDouble();
if (score != -1) {
totalScore += score;
count++;
}
} while (score != -1);
double averageScore = totalScore / count;
if (averageScore > bestScore) {
bestScore = averageScore;
bestPlayer = player;
}
System.out.printf("Average Score = %.2f\n", averageScore);
}
System.out.printf("Best Average Score = %.2f, best player = %d\n", bestScore, bestPlayer);
}
Just keep a variable to record the top average score every time as in topAverage in my example below. The code is same as your's except I changed the variable names for my readability.
public static void main(String[] args) throws NumberFormatException,
IOException {
double currentScore = 0;
double totalScore = 0;
int numScores = 0;
double averageScore = 0;
double topAverage = 0;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
for (int i = 0; i < 4; i++) {
do {
System.out.println("Enter Score");
currentScore = Double.parseDouble(br.readLine());
totalScore = totalScore + currentScore;
numScores += 1;
} while (currentScore != -1);
numScores-=1;
totalScore+=1;
averageScore = totalScore / numScores;
System.out.println("Average Score is " + averageScore);
if (topAverage < averageScore) {
topAverage = averageScore;
}
currentScore = 0;
totalScore = 0;
numScores = 0;
}
System.out.println("Top Average is " + topAverage);
}
Edit
#Andrei Nikolaenko posted the same answer before me, so consider that answer, I am adding this edit because I want to mention that my browser did not refresh on time to show me that the answer has already been posted.
This question already has answers here:
Getting the lowest and highest value from integers without using arrays?
(2 answers)
Closed 9 years ago.
I need this code to print out the lowest score entered and I'm sitting here for hours and I can't figure out how to do it.I know how to make it using arrays but I need to use for loops.Do you have any hints?
Example output:
How many scores? 3
Enter score 1: 90
Enter score 2: 80
Enter score 3: 100
Lowest score is 80
My code:
int score,numScore,count;
Scanner keyboard = new Scanner(System.in);
System.out.print("How many scores? ");
numScore = keyboard.nextInt();
for(count = 1; count <= numScore; count++){
System.out.print("Enter score " + count + ":");
score = keyboard.nextInt();
}
Maintain a variable that you compare against with each keyboard input.
int lowestScore = 100000;
for(count = 1; count <= numScore; count++){
System.out.print("Enter score " + count + ":");
score = keyboard.nextInt();
if (score < lowestScore) {
lowestScore = score;
}
}
Maintain a variable to find the lowest score like this
int lower = -1;
Inside for loop
if(lower == -1) {
lower = score;
} else if(score < lower) {
lower = score;
}
Finally lower has the required value
Simply save the lowest score in a variable and update it every time the lower score is encountered:
int lowestScore = 100;
for(count = 1; count <= numScore; count++){
System.out.print("Enter score " + count + ":");
score = keyboard.nextInt();
if(score < lowestScore){
lowestScore = score;
}
}
Added 3 lines
int score,numScore,count;
int minimum;
Scanner keyboard = new Scanner(System.in);
System.out.print("How many scores? ");
numScore = keyboard.nextInt();
for(count = 1; count <= numScore; count++){
System.out.print("Enter score " + count + ":");
score = keyboard.nextInt();
if (count == 1) minimum = score;
if (score < minimum) minimum = score;
}