Beginner java programming if-else statements inefficient code - java

My code is correct but it looks too big.I was wondering if it could be more efficient and with even fewer variables.Do you have any hints?Thanks
sample output
Enter three scores: 87 42 94
The lowest score was: 42
The average without the lowest score is: 90.5
The grade is: A
<code>
import java.util.Scanner;
public class GradeAverager
{
public static void main(String[] args)
{
int score1,score2,score3;
double average,average_no_lowest;
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter three scores: ");
score1 = keyboard.nextInt();
score2 = keyboard.nextInt();
score3 = keyboard.nextInt();
average = (score1 + score2 + score3) / 3.0;
System.out.println();
System.out.println("The average is: " + average);
if (score1 < score2 && score1 < score3)
System.out.println("The lowest score was:" + score1);
else if (score2 < score1 && score2 < score3)
System.out.println("The lowest score was:" + score2);
else if (score3 < score1 && score3 < score2)
System.out.println("The lowest score was:" + score3);
if (score1 < score2 && score1 < score3){
average_no_lowest = (score2 + score3)/2.0;
System.out.println("The average without the lowest score is: " + average_no_lowest);
if(average_no_lowest > 90)
System.out.print('A');
else if(average_no_lowest < 90 && average_no_lowest > 80 )
System.out.print('B');
else if(average_no_lowest > 70 && average_no_lowest < 80)
System.out.print('C');
else
System.out.print('D');
}
else if (score2 < score1 && score2 < score3){
average_no_lowest = (score1 + score3)/2.0;
System.out.println("The average without the lowest score is: " + average_no_lowest);
if(average_no_lowest > 90)
System.out.print('A');
else if(average_no_lowest < 90 && average_no_lowest > 80 )
System.out.print('B');
else if(average_no_lowest > 70 && average_no_lowest < 80)
System.out.print('C');
else
System.out.print('D');
}
else if (score3 < score1 && score3 < score2){
average_no_lowest =(score1 + score3)/2.0;
System.out.println("The average without the lowest score is: " + (score1 + score3)/2.0);
if(average_no_lowest > 90)
System.out.print('A');
else if(average_no_lowest < 90 && average_no_lowest > 80 )
System.out.print('B');
else if(average_no_lowest > 70 && average_no_lowest < 80)
System.out.print('C');
else
System.out.print('D');
}
}
}
</code>

Your section of code which reads
if(average_no_lowest > 90)
System.out.print('A');
else if(average_no_lowest < 90 && average_no_lowest > 80 )
System.out.print('B');
else if(average_no_lowest > 70 && average_no_lowest < 80)
System.out.print('C');
else
System.out.print('D');
}
is duplicated 3 times. Put it into a method.
Don't be worried about performance until it is a proven problem. Be worried about how easy it is to read and maintain the code.
Code has 2 audiences - the compiler and humans. Humans matter more than compilers.

Store the lowest score in a variable e.g. lowest_score.
and do the average by (total - lowest_score) / 2
It is the most efficient

You can use the following code,these have fewer lines of code and gives the same output as you want::
public static void main(String[] args) {
int score1, score2, score3, status;
double average, average_no_lowest;
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter three scores: ");
score1 = keyboard.nextInt();
score2 = keyboard.nextInt();
score3 = keyboard.nextInt();
average = (score1 + score2 + score3) / 3;
System.out.println("Average Score was:: " + average);
if (score1 < score2 && score1 < score3) {
status = 1;
System.out.println("The lowest score was:: " + score1);
} else if (score2 < score1 && score2 < score3) {
status = 2;
System.out.println("The lowest score was:: " + score2);
} else {
status = 3;
System.out.println("The lowest score was:: " + score3);
}
if (status == 1) {
average_no_lowest = (score2 + score3) / 2;
System.out.println("The average without the lowest score is: "
+ average_no_lowest);
} else if (status == 2) {
average_no_lowest = (score1 + score3) / 2;
System.out.println("The average without the lowest score is: "
+ average_no_lowest);
} else {
average_no_lowest = (score1 + score2) / 2;
System.out.println("The average without the lowest score is: "
+ average_no_lowest);
}
}

Related

Java arrays code in max and min

My project is about finding the average, minimum and maximum of students' grades and their standing, but it keeps showing me an error on the output.
Here are the names and the grades:
Students:
Alia Nahid Eiman Suad Lamia Salma Mai Wedad Haya Sanaa
Quiz:
10 20 50 70 80 50 30 90 60 40
Midterm:
30 80 100 40 80 70 70 80 50 30
Final Exam:
40 80 70 100 90 60 70 50 40 80
And here is the Java code:
package java_final_project;
import java.util.*;
public class Java_Final_Project {
static Scanner console = new Scanner(System.in);
public static void main(String[] args) {
// Declare inputs:
String letter1, letter2, letter3;
int min = Integer.MAX_VALUE;
int max = Integer.MIN_VALUE;
// Declare the four array structures
int[] quiz = new int[10];
int[] midterm = new int[10];
int[] finalexam = new int[10];
String[] students = new String[10];
// Input elements to the arrays
int counter, sum1 = 0;
int sum2 = 0;
int sum3 = 0;
double ave1, ave2, ave3;
int max1, max2, max3;
int min1, min2, min3;
for (counter = 0; counter < 10; counter++) {
System.out.println ("Enter student names and grades of quiz, midterm "
+ "and final with space between them");
students[counter] = console.next();
quiz[counter] = console.nextInt();
sum1 = sum1 + quiz[counter];
midterm[counter]= console.nextInt();
sum2 = sum2 + midterm[counter];
finalexam[counter]= console.nextInt();
sum3 = sum3 + finalexam[counter];
}
ave1 = sum1 / 10;
ave2 = sum2 / 10;
ave3 = sum3 / 10;
// min and max values
max1 = Math.max(quiz[counter], max);
max2 = Math.max(midterm[counter], max);
max3 = Math.max(finalexam[counter], max);
min1 = Math.min(quiz[counter], min);
min2 = Math.min(midterm[counter], min);
min3 = Math.min(finalexam[counter], min);
// if statement for the standing
// ave1
if (ave1 >= 90 && ave1 <= 100) {
letter1 = "E";
} else if (ave1 >= 70 && ave1 <= 80) {
letter1 = "G";
} else if (ave1 >= 50 && ave1 <= 60) {
letter1 = "S";
} else {
letter1 = "P";
}
// ave2
if (ave2 >= 90 && ave2 <= 100) {
letter2 = "E";
} else if (ave2 >= 70 && ave2 <= 80) {
letter2 = "G";
} else if (ave2 >= 50 && ave2 <= 60) {
letter2 = "S";
} else {
letter2 = "P";
}
//ave3
if (ave3 >= 90 && ave3 <= 100) {
letter3 = "E";
} else if (ave3 >= 70 && ave3 <= 80) {
letter3 = "G";
} else if (ave3 >= 50 && ave3 <= 60) {
letter3 = "S";
} else {
letter3 = "P";
}
// Display the elements of the four arrays
System.out.println("Here is the elements of the four arrays");
System.out.println("students" + "\t" + "quiz" + "\t" + "midterm" + "\t" + "finalexam");
for (counter = 0; counter < 10; counter++) {
System.out.println(students[counter] + "\t" + quiz[counter] + "\t" + midterm[counter] + "\t" + finalexam[counter]);
}
System.out.println("Summary Report:");
System.out.println();
System.out.println("students" + "\t" + "\t" + "Quiz" + "\t" + "\t" + "Midterm" + "\t" + "\t" + "FinalExam");
System.out.println();
System.out.println("Average" + "\t" + "\t" + ave1 + "\t" + "\t" + ave2 + "\t" + "\t" + ave3);
System.out.println();
System.out.println("Max" + "\t" + "\t" + max1 + "\t" + "\t" + max2 + "\t" + "\t" + max3);
System.out.println();
System.out.println("Min" + "\t" + "\t" + min1 + "\t" + "\t" + min2 + "\t" + "\t" + min3);
System.out.println();
System.out.println("Standing" + "\t" + "\t" + letter1 + "\t" + "\t" + letter2 + "\t" + "\t" + letter3);
}
}
The six lines where you set min1, min2, min3, max1, max2, max3 need to be up, inside the for loop where you gather the input; because you want to check after each input whether it's bigger or smaller than the current maximum and minimum. Where you have those lines at the moment, they can't possible work, because counter is no longer pointing to an entry in the array.
I'm not sure if you are allowed to use streams in your assignment. If you are then there is a much easier way of getting min, max, average in Java 8:
int[] scores = {1, 3, 6, 8, 10, 11, 2};
int max = Arrays.stream(scores).max();
int min = Arrays.stream(scores).min();
int avg = Arrays.stream(scores).average();
You don't really need to use loops often now that Java has streams.
I've figured out the codes and corrected some mistakes. Here's the updated java code and it worked :D! and I thank you for your comments and help :)
package java_final_project;
import java.util.*;
public class Java_Final_Project
{
static Scanner console = new Scanner(System.in);
public static void main(String[] args)
{
// Declare inputs:
String letter1, letter2, letter3;
double ave1, ave2, ave3;
// Declare the four array structures
int[] quiz = new int[10];
int[] midterm = new int[10];
int[] finalexam = new int[10];
String [] students = new String[10];
int [] scores = new int[100];
// Input elements to the arrays
int counter, sum1=0;
int sum2=0;
int sum3=0;
for ( counter = 0; counter < 10; counter++)
{
System.out.println ("Enter student names and grades of quiz, midterm "
+ "and final with space between them");
students[counter] = console.next();
quiz[counter]= console.nextInt();
sum1 = sum1 + quiz[counter];
midterm[counter]= console.nextInt();
sum2 = sum2 + midterm[counter];
finalexam[counter]= console.nextInt();
sum3 = sum3 + finalexam[counter];
}
// max and min values for the quiz
int minGrade = quiz[0];
int maxGrade = quiz[0];
for (int i = 0; i < 10; i++)
{
if (minGrade > quiz[i])
minGrade = quiz[i];
if (maxGrade < quiz[i])
maxGrade = quiz[i];
}
// max and min values for the midterm
int minGrade1 = midterm[0];
int maxGrade1 = midterm[0];
for (int i = 0; i < 10; i++)
{ if (minGrade1 > midterm[i])
minGrade1 = midterm[i];
if (maxGrade1 < midterm[i])
maxGrade1 = midterm[i];}
// max and min values for the final
int minGrade2 = finalexam[0];
int maxGrade2 = finalexam[0];
for (int i = 0; i < 10; i++)
{if (minGrade2 > finalexam[i])
minGrade2 = finalexam[i];
if (maxGrade2 < finalexam[i])
maxGrade2 = finalexam[i];}
//calculate the average of quiz, midterm, final
ave1 = sum1/10;
ave2 = sum2/10;
ave3 = sum3/10;
// if statement for the standing
// ave1
if (ave1 > 90 && ave1 > 100)
{letter1 = "E";}
else if (ave1 > 70 && ave1 > 80)
{letter1 = "G" ;}
else if (ave1 > 50 && ave1 > 60)
{letter1 = "S";}
else
{letter1 = "P";}
// ave2
if (ave2 > 90 && ave2 > 100)
{letter2 = "E";}
else if (ave2 > 70 && ave2 > 80)
{letter2 = "G" ;}
else if (ave2 > 50 && ave2 > 60)
{letter2 = "S";}
else
{letter2 = "P";}
//ave3
if (ave3 > 90 && ave3 > 100)
{letter3 = "E";}
else if (ave3 > 70 && ave3 > 80)
{letter3 = "G" ;}
else if (ave3 > 50 && ave3 > 60)
{letter3 = "S";}
else
{letter3 = "P";}
// Display the elements of the four arrays
System.out.println (" Here is the elements of the four arrays");
System.out.println ("students"+"\t"+"quiz"+"\t"+"\t"+"midterm"+"\t"+"\t"+"finalexam");
for ( counter = 0; counter < 10; counter++)
{
System.out.println (students[counter]+"\t"+"\t"+quiz[counter]+"\t"+"\t"+midterm[counter]
+"\t"+"\t"+finalexam[counter]);
}
System.out.println (" ");
System.out.println ("Summary Report:");
System.out.println ("\t"+"\t"+"Quiz"+"\t"+"\t"+"Midterm"+"\t"+"\t"+"FinalExam");
System.out.println ("Average"+"\t"+"\t"+ave1+"\t"+"\t"+ave2+"\t"+"\t"+ave3);
System.out.println ("max"+ "\t"+"\t"+maxGrade+ "\t"+"\t"+ maxGrade1+ "\t"+"\t"+ maxGrade2);
System.out.println ("min"+ "\t"+"\t"+minGrade+ "\t"+"\t"+ minGrade1+ "\t"+"\t"+ minGrade2);
System.out.println ();
System.out.println ("Standing"+ "\t"+ letter1+ "\t"+ "\t"+ letter2+ "\t"+"\t"+ letter3);
}
}

Java - I'm coding my first project. It's blackjack, but I've ran into some trouble

I am new to programming. I was trying to make blackjack and I ran into some problems.
My console output:
Would you like to play again? y/n
y
You have: $50
Whats your bet:
12
You get a 7 and a 10
Your total is 17
The dealer has a 9 11 showing
Would you like to hit? y/n :
n
The dealer has 20 //Here it is supposed to say You lost blah blah blah
Would you like to play again? y/n //but its skipping to System.println("play again");
package loops;
import java.util.Scanner;
import java.util.Random;
public class loops {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
char hit = 0;
char playAgain = 0;
String dolphin = "banana";
int c = 5;
int win = 0;
int[] cards = {2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,6,6,6,6,7,7,7,7,8,8,8,8,9,9,9,9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,11,11,11,11};
int bet, money = 999999999, cardValue = 0, dealersValue = 0;
if(money == 999999999){
System.out.println("How much money would you like to start with?");
money = reader.nextInt();
}
do {
shuffleArray(cards);
System.out.println("You have: $" + money);
System.out.println("Whats your bet: ");
bet = reader.nextInt();
if(bet > money){
System.out.println("You cannot bet over " + money + "!");
System.exit(0);
break;
}
System.out.println("You get a " + cards[0] + " and a " + cards[1]);
cardValue = cards[0] + cards[1];
System.out.println("Your total is " + cardValue);
if(cardValue == 21){
win = 1;
}
if(cardValue > 21){
win = 2;
}
if(win != 2){
int i = 9;
System.out.println("The dealer has a " + cards[7] + " " + cards[8] + " showing");
dealersValue = cards[7] + cards[8];
System.out.println("Would you like to hit? y/n : ");
hit = reader.next().charAt(0);
while(dealersValue <= 17){
if(dealersValue <= 17){
dealersValue = cards[7] + cards[8] + cards[i];
}
if(dealersValue <= 17){
dealersValue = cards[7] + cards[8] + cards[i] + cards[i];
}
if(dealersValue <= 17){
dealersValue = cards[7] + cards[8] + cards[i] + cards[i] + cards[i];
}
if(cards[i] > 11 && dealersValue > 21){
cards[i] = 1;
}
if(cards[7] > 11 && dealersValue > 21){
cards[7] = 1;
}
if(cards[8] > 11 && dealersValue > 21){
cards[8] = 1;
}
i++;
}}
while(hit == 'y'){
System.out.println("You get a " + cards[c]);
cardValue = cardValue + cards[c];
System.out.println("Your total is " + cardValue);
if(cardValue > 21){
if(cards[5] > 11 && cardValue > 21){
cards[5] = 1;
System.out.println("To avoid busting, you 11 changes to 1");
}
if(cards[6] > 11 && cardValue > 21){
cards[6] = 1;
System.out.println("To avoid busting, you 11 changes to 1");
}
if(cards[7] > 11 && cardValue > 21){
cards[7] = 1;
System.out.println("To avoid busting, you 11 changes to 1");
}
if(cards[8] > 11 && cardValue > 21){
cards[8] = 1;
System.out.println("To avoid busting, you 11 changes to 1");
}
if(cards[9] > 11 && cardValue > 21){
cards[9] = 1;
System.out.println("To avoid busting, you 11 changes to 1");
}
if(cardValue > 21){
break;
}
}
System.out.println("Would you like to hit? y/n : ");
hit = reader.next().charAt(0);
c++;
if(hit =='n'){
System.out.println("You stay!");
cardValue = cardValue + 0;
break;
}
}
System.out.println("The dealer has " + dealersValue);
if(dealersValue > 21){
win = 1;
}
if(cardValue > 21){
win = 2;
}
if(cardValue == 21){
win = 1;
}
if(dealersValue == 21){
win = 2;
}
if (dealersValue > cardValue && dealersValue > 21){
win = 2;
}
if (dealersValue == cardValue){
win = 2;
}
if(dealersValue < cardValue && cardValue <=21) {
win = 1;
}
if(dealersValue == 21 && dealersValue != cardValue || dealersValue == 21 && dealersValue == cardValue || cardValue > 21){
win = 2;
}
if(cardValue == 21 && dealersValue != cardValue || dealersValue > 21){
win = 1;
}
if(win == 1){
System.out.println("You won "+bet*1 + " dollars!");;
System.out.println("Your total balance is " + money);
}
if(win == 2){
System.out.println("You lost "+bet*1 + " dollars!");;
System.out.println("Your total balance is " + money);
}
if(win == 3){
System.out.println("You lost "+bet*1 + " dollars!");;
System.out.println("Your total balance is " + money);
}
if(money <= 0){
System.out.println("You are out of money!");
System.exit(0);
}
System.out.println("Would you like to play again? y/n ");
playAgain = reader.next().charAt(0);
if(playAgain == 'n'){
System.exit(0); }
win = 0;
} while (playAgain == 'y');
}
static void shuffleArray(int[] cards){
Random rnd = new Random();
for (int i = cards.length - 1; i > 0; i--)
{
int index = rnd.nextInt(i + 1);
int a = cards[index];
cards[index] = cards[i];
cards[i] = a;
}
}
}
I've combed through the code multiple times, looking for where I went wrong, like maybe a } where it shouldn't be, but I could not find anything. I think it could use some fresh eyes!
After I get this code working, I'm planning on trying again with an object oriented approach.
The set of if statements that set the variable "win" are incorrect.
Walking through the code with the example given (dealer has 20, player has 17), the variable "win" is never set thus all the statements printing out "You lost" and "You won" are skipped.
It is very likely that in this line
if (dealersValue > cardValue && dealersValue > 21){
you meant
dealersValue < 21
which would then be cause win to be set to 2 and the correct output to be displayed.
Debugging Tip: Walk through the code with your IDE. If you step through line by line, you should immediately see it skip of setting the "win" variable.
Good luck in learning programming! It's fun but very frustrating :)

Read and print from a text file

Ok so I'm supposed to be reading and printing from a text file with the code yet every time I run I get a "java.utilNoSuchElementException" on line 31 "grade = in.nextInt();". The current text file is
2 80 97
5 69 79 89 99 58
7 60 70 80 90 100 0 59
where the first number is the number of scores in each section, each section is supposed to be counted (ie. 1, 2, 3) Anyways one problem at a time. here's the current code.
import java.util.Scanner;
import java.io.*;
public class Prog2
{
public static void main (String args []) throws IOException
{
Scanner in = new Scanner (new File ("test1.txt"));
int Lowest, Highest, grade = 0;
float section_average, class_average;
int count = 0, A = 0, B = 0, C = 0, D = 0, F = 0, total_number_of_sections = 0, total_number_of_scores = 0, number = 0;
while (in.hasNextInt())
{
number = in.nextInt();
System.out.println (in.nextInt());
number ++;
while (count < number)
{
grade = in.nextInt();
total_number_of_sections += number;
total_number_of_scores += grade;
total_number_of_scores ++;
count++;
}
}
if (number > 0)
{
System.out.println ("Scores for section "+count);
}
else
{
System.out.println ("Scores for section 0");
}
if (grade >= 90)
{
A ++;
}
if (grade >= 80 && grade < 90)
{
B ++;
}
if (grade >= 70 && grade < 80)
{
C ++;
}
if (grade >= 60 && grade < 70)
{
D ++;
}
if (grade < 60)
{
F ++;
}
System.out.println (" ");
System.out.println ("Scores for section "+count);
System.out.println ("A's" + A);
System.out.println ("B's" + B);
System.out.println ("C's" + C);
System.out.println ("D's" + D);
System.out.println ("F's" + F);
System.out.println ("Lowest Score: ");
System.out.println ("Highest Score: ");
System.out.println (" ");
System.out.println (" ");
System.out.println ("Total number of sections: " + total_number_of_sections);
System.out.println ("Total number of scores: " + total_number_of_scores);
System.out.println ("Class Average: ");
}
}
try this
while (in.hasNextInt())
{
count = 0;
number = in.nextInt();
System.out.println (in.nextInt());
while (in.hasNextInt())
{
grade = in.nextInt();
total_number_of_sections += number;
total_number_of_scores += grade;
total_number_of_scores ++;
if(++count == number ){ break;}
}
}

Proper msg display

I don't get any errors but I want to display this msg "No discount. Your total is $_"
using this code:
if (!(sales < 10))
System.out.print("No discount. " +
"Your total is: $" + (int)total);
inside this code:
if (!(sales < 10))
System.out.print("No discount. " +
"Your total is: $" + (int)total);
else if (sales >= 10 || sales <= 19)
rate = 0.20;
else if (sales >= 20 || sales <=49)
rate = 0.30;
else if (sales >= 50 || sales <=99)
rate = 0.40;
else if (sales > 100)
rate = 0.50;
else
System.out.println("Your discount is $" + (int)discount +
". Your total is: $" + (int)total);
and it does show but i only want it to show when sales< 10
but if sales is NOT < 10 then i want it to show "Your discount is $___. Your total is $____."
any help will be very much appreciated. thanks for your time.
whole code:
import java.util.Scanner;
public class SoftwareSales
{
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
int sales = 99;
int quantity;
double total;
double rate = 0;
double discount;
System.out.print ("Enter amount of packages purchased: ");
quantity = keyboard.nextInt();
total = quantity * sales;
discount = total * rate;
total = total - discount;
if (sales < 10) {
if (sales >= 10 || sales <= 19)
rate = 0.20;
else if (sales >= 20 || sales <=49)
rate = 0.30;
else if (sales >= 50 || sales <=99)
rate = 0.40;
else if (sales > 100)
rate = 0.50;
System.out.println("Your discount is $" + (int)discount +
". Your total is: $" + (int)total);
} else {
System.out.print("No discount. " +
"Your total is: $" + (int)total);
}
}
}
Try this:
if (sales > 10) {
if (sales >= 10 || sales <= 19)
rate = 0.20;
else if (sales >= 20 || sales <=49)
rate = 0.30;
else if (sales >= 50 || sales <=99)
rate = 0.40;
else if (sales > 100)
rate = 0.50;
System.out.println("Your discount is $" + (int)discount +
". Your total is: $" + (int)total);
} else {
System.out.print("No discount. " +
"Your total is: $" + (int)total);
}
So why are you testing for the exact opposite of what you want to do? Notice the exclamation mark (!) which inverts your sales test in your first if. Remove that and your code should work as intended.

Stuck on Java program that tallies grades and shows results

I'm taking a beginners course in Java and they asked us to:
Write a program to tally the number of A's, B's, C's, D's and F's based upon a list of scores entered by a user.
After all the scores are entered, the program must display a
horizontal bar graph of the number tallied for each grade like that shown in the Operation section.
The tally graph must display a single '*' for each unit tallied.
When a user enters a -1, the program must display the final graph and
exit.
The output of your program must display prompts and a tally graph
like that shown in the Operation section above.
You may assume that a user will enter numbers only.
Operation:
The program starts and prompts you to either enter a test score or end
the program by entering a -1. Like the following:
Number of A's: 0
Number of B's: 0
Number of C's: 0
Number of D's: 0
Number of F's: 0
Enter a score (%) or -1 to end: 90
As you enter each score, the application decides whether the score is
an A, B, C, D or F and adds one to the letter-grade tally. Like the
following:
Number of A's: 1
Number of B's: 0
Number of C's: 0
Number of D's: 0
Number of F's: 0
Enter a score (%) or -1 to end: 95
Each time you enter a score, the program updates the tally. Like the following:
Number of A's: 2
Number of B's: 0
Number of C's: 0
Number of D's: 0
Number of F's: 0
Enter a score (%) or -1 to end: -1
When you are done entering scores, the program displays a horizontal
bar graph of the tally for A's, B's, C's, D's and F's. Like the
following:
A's: **
B's:
C's:
D's:
F's:
Specifications:
Numerical Grade Letter Grade
greater than or equal to 90 A
less than 90 but greater than or equal to 80 B
less than 80 but greater than or equal to 70 C
less than 70 but greater than or equal to 60 D
less than 60 F
When the program ends, display the number of scores, average score, and best score.
Example:
Number of scores: 2
Average score: 92.5
Best score: 95.0
We have also been instructed to code in at least two methods : one that has a void and one that returns something.
So far I have only been able to tally up the scores entered, but I don't seem to be able to wrap my head around recording all the inputs and calculating the average and picking out the best score
This is what I have so far :
import java.util.*;
public class ScoreTally {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int aCount = 0;
int bCount = 0;
int cCount = 0;
int dCount = 0;
int fCount = 0;
int scoreCount = -1;
double score = 0;
while (score != -1) {
if (score >= 90)
aCount++;
else if ((score < 90) && (score >= 80))
bCount++;
else if ((score < 80) && (score >= 70))
cCount++;
else if ((score < 70) && (score >= 60))
dCount++;
else if ((score < 60) && (score > 0))
fCount++;
System.out.println("Number of A's: " + aCount);
System.out.println("Number of B's: " + bCount);
System.out.println("Number of C's: " + cCount);
System.out.println("Number of D's: " + dCount);
System.out.println("Number of F's: " + fCount);
System.out.print("Enter a score (%) or -1 to end: ");
score = input.nextDouble();
scoreCount++;
}
if (score == -1)
System.out.println("Number of scores: " + scoreCount);
}
}
Use a function to return the greatest number to get your best score.
And another function to print the final graph.
That should take care of the two function requirement.
Also, make the loop an exit-controlled one, as it has to run atleast once.
As a coding practice, you should not be using star imports(import java.util.*) instead use only what you need.
Also, good work on setting the scoreCount to -1 in the beginning.
import java.util.Scanner;
public class ScoreTally {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int aCount = 0;
int bCount = 0;
int cCount = 0;
int dCount = 0;
int fCount = 0;
int scoreCount = -1;
double score;
double totalScore = 0;
double bestScore = -1;
do {
System.out.println("Number of A's: " + aCount);
System.out.println("Number of B's: " + bCount);
System.out.println("Number of C's: " + cCount);
System.out.println("Number of D's: " + dCount);
System.out.println("Number of F's: " + fCount);
System.out.print("Enter a score (%) or -1 to end: ");
score = input.nextDouble();
if (score >= 90) {
aCount++;
} else if ((score < 90) && (score >= 80)) {
bCount++;
} else if ((score < 80) && (score >= 70)) {
cCount++;
} else if ((score < 70) && (score >= 60)) {
dCount++;
} else if ((score < 60) && (score > 0)) {
fCount++;
}
scoreCount++;
totalScore = totalScore + score;
bestScore = greaterNumber(bestScore, score);
} while (score != -1);
printGraph('A', aCount);
printGraph('B', bCount);
printGraph('C', cCount);
printGraph('D', dCount);
printGraph('F', fCount);
System.out.println("Number of scores: " + scoreCount);
System.out.println("Average scores: " + totalScore / scoreCount);
System.out.println("Best scores: " + bestScore);
}
public static void printGraph(char grade, int count) {
System.out.print("Number of " + grade + "'s: ");
for (int i = 0; i < count; i++) {
System.out.print("*");
}
System.out.println();
}
public static double greaterNumber(double firstNum, double secondNum) {
if (firstNum >= secondNum) {
return firstNum;
} else {
return secondNum;
}
}
}
To begin with you already have the code to tally the results.
int aCount = 0;
int bCount = 0;
int cCount = 0;
int dCount = 0;
int fCount = 0;
int scoreCount = -1;
What you need is another field that will hold the total score i.e.
int totalScore = 0;
You need to prompt for the first score before you enter the while loop otherwise it won't run properly the first iteration. At the end (or the beginning) you need to update totalScore with whatever was the input for that round, and not update it if the input was -1.
The average score will just be the totalScore/scoreCount you should compute that after you finish the while loop.
For the best score you can have another field for int = maxScore
you can update it every iteration of the loop with
maxScore = Math.max(maxScore, score);
Math.max returns the maximum of the two numbers.
It's rather simple. Declare 2 variables, one for having avgScore, one for in beginning of your program.
double bestScore = 0.0;
double avgScore = 0.0;
double totalScore = 0.0;
while (score != -1) {
totalScore = totalScore + score;
if(score > bestScore)
bestScore = score;
if (score >= 90)
aCount++;
else if ((score < 90) && (score >= 80))
bCount++;
else if ((score < 80) && (score >= 70))
cCount++;
else if ((score < 70) && (score >= 60))
dCount++;
else if ((score < 60) && (score > 0))
fCount++;
System.out.println("Number of A's: " + aCount);
System.out.println("Number of B's: " + bCount);
System.out.println("Number of C's: " + cCount);
System.out.println("Number of D's: " + dCount);
System.out.println("Number of F's: " + fCount);
System.out.print("Enter a score (%) or -1 to end: ");
score = input.nextDouble();
scoreCount++;
}
if (score == -1){
System.out.println("Number of scores: " + scoreCount);
avgScore = totalScore/scoreCount;
System.out.println("Best Score: " + bestScore);
System.out.println("Avg Score: " + avgScore);
}
Also for displaying the chart you can use your final tallies.

Categories