Having Trouble with Correct output from If statement [closed] - java

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I could use some help with an assignment. The user has to enter the number of students and then enter scores and I have to find the best score and assign a grade accordingly.
Grade is A if score is >= best-10
Grade is B if score is >= best-20
Grade is C if score is >= best-30
Grade is D if score is >= best-40
Grade is F otherwise
My program is not producing the correct grades at the moment and I tried putting another for loop right before my if but nothing changed and then I tried using another variable (j instead of i) but I'm sort of stuck. I'm new to java so any help would be appreciated, and thank you in advance :)
Here is an example of the input and output:
Enter the number of students: 4
Enter 4 scores: 45 90 78 23
Student 0 grade is: A
Student 1 grade is: A
Student 2 grade is: A
Student 3 grade is: C
It's hard to tell if the best score is being determined because it gives the same score to other numbers, this happens with many other numbers as input.
``````````````````````````````````````````````
import java.util.Scanner;
public class Main
{
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter the number of students: ");
int students = input.nextInt();
int[] grades = new int [students];
System.out.print("Enter " + students + " scores: ");
for(int i=0; i<students; i++){
grades[i] = input.nextInt();
}
int max = grades[0];
for(int i = 0; i<grades.length; i++){
if(grades[i] > max){
max = grades[i];
}
for(i = 0; i<grades.length; i++){
if (grades [i] >= max-10){
System.out.println("Student " + i + " score is: A");
}else if (grades[i] >= max-20){
System.out.println("Student " + i + " grade is: B");
}else if (grades [i] >= max-30){
System.out.println("Student " + i + " grade is: C");
}else if (grades[i] >= max-40){
System.out.println("Student " + i + " grade is: D");
}else{
System.out.println("Student " + i + " grade is: F");
}
}
}
}
}
`````````````````````````````````````````

Generally your code is fine, there was an issue with calculating max grade:
int max = grades[0];
for(int i = 1; i < grades.length; i++ ) {
if(grades[i] > max) {
max = grades[i];
}
} // this loop should end before scoring all students
for (int i = 0; i < grades.length; i++ ) {
char score = 'F';
if (grades[i] >= max-10) score = 'A';
else if (grades[i] >= max-20) score = 'B';
else if (grades[i] >= max-30) score = 'C';
else if (grades[i] >= max-40) score = 'D';
System.out.println("Student " + i + " grade=" + grades[i]+ ", score is: " + score);
}
Output:
Student 0 grade=45, score is: F
Student 1 grade=90, score is: A
Student 2 grade=78, score is: B
Student 3 grade=23, score is: F
Note: What if the best grade is 50 out of 100, should the students with grades from 40 to 50 still get score 'A'? :)

Related

Filling an array with doubles from user in a given range

So it's time to come back to the users of stackoverflow for help again on an assignment.
I'm supposed to fill an array with a size of 10 with doubles given from the user. The entered numbers are supposed to be grades so they have to be in the range of 0 - 100. Anything out of the range (more, less, or incorrect characters) are not saved to the array and the user is prompted to try again at the given index of the array. After either the array is filled to the max value or the user presses enter to skip, the program is supposed to return the grades entered in order and display the average.
public static final SIZE = 10;
Scanner userIn = new Scanner(System.in);
double[] grades = new double [SIZE];
int counter = 0;
int counterList = 1;
boolean exit = false;
String sTemp = "";
double gradeNum = 0;
double avrGrade = 0.0;
double sum = 0;
while((counter < SIZE) && (!exit)) {
System.out.println("Enter grade " + counterList +
", or press enter to quit.");
sTemp = userIn.nextLine();
counterList++;
if(sTemp.length() < 1) {
exit = true; //ending for loop
} else {
gradeNum = Double.parseDouble(sTemp);
grades[counter] = gradeNum;
counter++;
} //else statement
} //end of while loop
counterList = 1;
System.out.println("You entered " + counter + " grades total.");
for(int i = 0; i <= counter; i++) {
System.out.println("Your grade " + counterList + " is " + grades[i]);
counterList++;
}
for(int i = 0; i < grades.length; i++)
sum += grades[i];
System.out.println("The average grade is: " + sum / grades.length);
So I finished taking my user's input and calculating the average but I'm having trouble setting the range and not saving the invalid inputs. I also feel like once I started to struggle I got really sloppy and there might be stuff going on in there that's not needed. Let me know anything helps!
An example of what the program should output given different scenarios
You can trim down your code. There are variables that you don't require. Explanations after the code.
import java.util.Scanner;
public class GradeAvg {
private static final int SIZE = 10;
public static void main(String[] args) {
Scanner userIn = new Scanner(System.in);
double[] grades = new double [SIZE];
int counter = 0;
String sTemp = "";
double sum = 0;
while(counter < SIZE) {
System.out.println("Please enter grade " + (counter + 1) + ": ");
sTemp = userIn.nextLine();
if (sTemp.isEmpty()) {
break;
}
try {
grades[counter] = Double.parseDouble(sTemp);
}
catch (NumberFormatException xNumberFormat) {
System.out.println("That wasn't a valid percentage, I need a number between 0 - 100. Try again.");
continue;
}
if (grades[counter] < 0 || grades[counter] > 100) {
System.out.println("That wasn't a valid percentage, I need a number between 0 - 100. Try again.");
continue;
}
sum += grades[counter];
counter++;
} //end of while loop
for (int i = 0; i < counter; i++) {
System.out.println("grade " + (i + 1) + ": " + grades[i]);
}
System.out.println();
System.out.println("number of valid grades entered: " + counter);
System.out.println();
System.out.println("average: " + sum / counter);
}
}
After accepting the user input, first check if the user simply pressed <ENTER> without entering a value. I used method isEmpty(), of class java.lang.String, to do this check. If the user simply pressed <ENTER>, you need to exit the while loop. This is what break does. So no need for boolean variable exit.
Variable counter is all you need to both keep track of how many grades have been entered and which index of array grades needs to be assigned a value, so no need for variable counterList.
If an invalid value is entered, continue skips the rest of the while loop and starts a new loop iteration. Think of it as a sort of goto that jumps back to the statement:
while (counter < SIZE)
You can assign a value directly to an element in array grades so no need for variable gradeNum.
You can update variable sum inside the while loop so no need for the extra for loop in order to calculate the average. By the way, your calculation of the average is incorrect since you are dividing by the size of array grades and not by the actual number of grades that were entered. Adding up all the elements in array grades still gives you the correct sum since all elements of the array are implicitly initialized to 0 (zero).
I changed what the program displays on the screen so as to match your example of what the program should output given different scenarios.
Here is the output according to the sample you provided.
Please enter grade 1:
A
That wasn't a valid percentage, I need a number between 0 - 100. Try again.
Please enter grade 1:
100
Please enter grade 2:
Bob
That wasn't a valid percentage, I need a number between 0 - 100. Try again.
Please enter grade 2:
41.5
Please enter grade 3:
-7
That wasn't a valid percentage, I need a number between 0 - 100. Try again.
Please enter grade 3:
grade 1: 100.0
grade 2: 41.5
number of valid grades entered: 2
average: 70.75
I made some adjustments:
final int SIZE = 10;
Scanner userIn = new Scanner(System.in);
double[] grades = new double [SIZE];
int counter = 0;
String sTemp = "";
double gradeNum = 0;
double sum = 0;
while(counter < SIZE) {
boolean err = false;
System.out.println("Enter grade " + (counter + 1) +
", or press enter to quit.");
sTemp = userIn.nextLine();
try {
gradeNum = Double.parseDouble(sTemp);
} catch(NumberFormatException ex)
{
err = true;
}
if(sTemp.length() < 1) {
break; //ending the loop
} else if(gradeNum <= 100 && gradeNum >= 0 && !err)
{
grades[counter] = gradeNum;
counter++;
} else
{
System.out.println("That wasn't a valid percentage, I need a number between 0 - 100. Try again.");
}
} //end of while loop
userIn.close(); //closing the Scanner
System.out.println("You entered " + counter + " grades total.");
for(int i = 0; i < counter; i++) {
System.out.println("Your grade " + (i + 1)+ " is " + grades[i]);
}
for(int i = 0; i < counter; i++) {
sum += grades[i];
}
System.out.println("\nNumber of valid grades entered: " + counter + "\n");
System.out.println("The average grade is: " + sum / counter);
}
This seems to work, I made some corrections (like SIZE declaration, took out the println from the last loop, replaced exit with a break statement, ...). The most relevant changes are the input checks and the average grade calculation (I used counter instead of grades.length because it is always 10). The try/catch checks if the input string contains only numbers.
(sorry for bad english, just ask if something isn't clear)

Read Scores from text file and sort into array

Im trying to get my test score program to work. Whenever I type in the pathfile to read from the text file the program would read 4 out of the 5 numbers that are there.Also, no matter what number there are it is always going to display my minimum as 0 when it is not true. Any help is truly appreciated!
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Arrays;
import java.util.Scanner;
public class Exam{
public static void main(String[] args) throws IOException {
System.out.println("Welcome!" + "\n");
//File location
System.out.println("Where is the data file:");
Scanner userInput = new Scanner(System.in);
String userFile = userInput.nextLine();
int i = 0;
int scores[] = readScores(userFile);
System.out.println("Minimum score: " + scores[0]);
System.out.println("Maximum score: " + scores[(scores.length - 1)]);
//Average Calculation
double gradesTotal = 0;
for (i=0; i<scores.length; ++i){
gradesTotal = gradesTotal + scores[i];
}
double mean = gradesTotal/scores.length;
System.out.println("Average score: " + mean);
//Mean Calculation
double median;
if (scores.length % 2 == 0)
median = ((scores[(scores.length/2) - 1]) + scores[(scores.length/2)]) / 2;
else
median = scores[(scores.length/2)];
System.out.println("Median score: " + median + "\n");
//Number of Grades
int gradeA = 0;
int gradeB = 0;
int gradeC = 0;
int gradeD = 0;
int gradeF = 0;
for (i=0; i<scores.length; i++)
{
if (scores[i] >= 90 && scores[i] <=100){
gradeA++;
}
else if (scores[i] <= 89 && scores[i] >=80){
gradeB++;
}
else if (scores[i] <= 79 && scores[i] >=70){
gradeC++;
}
else if (scores[i] <= 69 && scores[i] >=60){
gradeD++;
}
else if (scores[i] <= 59 && scores[i] >=1){
gradeF++;
}
}
System.out.println("Scores by letter grade: ");
System.out.println("A: " + gradeA);
System.out.println("B: " + gradeB);
System.out.println("C: " + gradeC);
System.out.println("D: " + gradeD);
System.out.println("F: " + gradeF);
}
//Reads the data from the submitted file
private static int[] readScores(String userFile) throws FileNotFoundException
{
File inputFile = new File(userFile);
Scanner stats = new Scanner(inputFile);
try {
int scores[] = new int[stats.nextInt()];
int i = 0;
while (stats.hasNext()){
scores[i] = stats.nextInt();
i++;
}
System.out.println("\n" + "There are " + (i) + " scores" + "\n");
Arrays.sort(scores);
return scores;
}
finally {
stats.close();
}
}
}
Text file:
72
31
13
39
74
Program output:
There are 4 scores
Minimum score: 0
Maximum score: 74
Average score: 2.1805555555555554
Median score: 0.0
Number of scores by letter grade:
A: 0
B: 0
C: 1
D: 0
F: 3
int scores[] = new int[stats.nextInt()];
here you take the first of your values and then you dont have it where you need it.
That is probably also the reason why your calculations are so messed up. you create an array of lenght 72 and use that lenght for the number of values.
Maybe you want to use a list instead. It allows you to add as many values as you want without specifying a number like you have to do when you use an array.

Getting highest grade and printing it out using arrays

I want to write a program that can read scores, get the best scores, and assign grades based on that. I have the general idea so far, my problem is figuring out how to incorporate the necessary for-loops. Another problem I have is figuring out how to change line
----(String s1=input.next();) and have the final answer print out the number of entries entered.
I must also use the equation
Grade is A if best score if >= best-10
Grade is B if best score if >= best-20
Grade is C if best score if >= best-30
Grade is D if best score if >= best-40
Ex solution:
Enter number of Students: 4
Enter 4 scores: 40 55 70 58
Student 0 score is 40 and grade is C
Student 1 score is 55 and grade is B
etc. to 4 students.
public class Lab_7_1{
public static void main(String[] args){
java.util.Scanner input=new java.util.Scanner(System.in);
System.out.print("Enter the number of students: ");
int n1=input.nextInt();
int [] number=new int[n1];
System.out.print("Enter "+n1+" Scores: ");
String s1=input.next();
}
}
Try something like this:
public class Lab_7_1{
public static void main(String[] args){
java.util.Scanner input=new java.util.Scanner(System.in);
System.out.print("Enter the number of students: ");
int n1=input.nextInt();
int [] number=new int[n1];
System.out.print("Enter "+n1+" Scores: ");
for (int i = 0; i < number.length; i++) {
number[i]=input.nextInt();
int b=i+1;
System.out.println("Score "+b+": "+number[i]);
}
int best = number[0];
for (int i = 0; i < number.length; i++) {
if (number[i]>best) best = number[i];
}
System.out.println("The best score is: "+best);
for (int i = 0; i < number.length; i++) {
if(number[i]>=best-20 && number[i]<=best-10) System.out.println("For score "+number[i] +" you get B grade.");
if(number[i]>=best-30 && number[i]<=best-20) System.out.println("For score "+number[i] +" you get C grade.");
if(number[i]>=best-40 && number[i]<=best-30) System.out.println("For score "+number[i] +" you get D grade.");
}
}
}`
Next step (using a for loop):
for (int i = 0; i < n1; i++) {
number[i] = input.nextInt();
}
Now that you've learned how to write a for loop, you can loop through the numbers to find the highest number, then do it again to print the results.

java - break loop with invalid input

I am creating a program that calculates users grades based on their input. All is good except that I need to deal with users inputting invalid entries.
Example: The user enters three exam scores on a single line (95 90 87 for example). If one of these scores is negative (95 90 -87) I need the program to NOT enter those three scores and assign a letter grade and instead prompt the user to re-enter the scores correctly.
Here is my code:
public class GradeCalculator {
public static void main(String[] args) {
int classSum = 0; // variable used to hold sum of entire classes exams
int classExams = 0; // variable used to hold number of exams taken by whole class
Scanner s = new Scanner(System.in);
System.out.println("Welcome to Gradecalculator!");
System.out.println("Please enter the number of students:");
int students = s.nextInt();
System.out.println("Please enter the number of exams:");
int exams = s.nextInt();
int i = 0;
int studentnumber = 1;
int sum = 0;
while (i < students) { // loop until it matches number of students entered above
i++;
sum = 0;
System.out.println("Enter student " + studentnumber++ + "'s name :");
String studentname = s.next();
System.out.println("Enter exam scores :");
int input = 0;
for (; input < exams; input++) {
int n = s.nextInt();
sum+=n;
if (n < 0) {
System.out.println("Invalid exam scores, reenter: "); //if one of the scores entered is negative, display message
}
}
double average = sum/exams; // assign letter grade based on average of exams
if (average <= 100 && average >= 90) {
System.out.println("Letter grade: A");
System.out.println(studentname + " gets 4 stars! ****");
} if (average <= 89 && average >= 80) {
System.out.println("Letter grade: B");
System.out.println(studentname + " gets 3 stars! ***");
} if (average <= 79 && average >= 70) {
System.out.println("Letter grade: C");
System.out.println(studentname + " gets 2 stars! **");
} if (average <= 69 && average >= 60) {
System.out.println("Letter grade: D");
System.out.println(studentname + " gets 1 star! *");
} if (average <= 59) {
System.out.println("Letter grade: F");
System.out.println(studentname + " gets 0 stars!");
}
classSum += sum; // add sum of this student's scores to the classSum
classExams += exams; // add exams taken by this student to amount of exams taken by whole class
}
int classAverage = classSum/classExams; // compute class average
System.out.println("Class statistics:");
System.out.println("\tAverage: " + classAverage);
}
}
Clearly I have this code in the wrong place:
if (n < 0) {
System.out.println("Invalid exam scores, reenter: "); //if one of the scores entered is negative, display message
}
}
Because this is the output I get when entering a negative score:
Enter exam scores :
70 70 -70
Invalid exam scores, reenter:
Letter grade: F
joe gets 0 stars!
As you can see, it still assigns a letter grade and stars and asks for the next student's name. I need it to instead ask to re-enter this student's scores. Can't figure out how to do that.
You can subtract one from the input inside that for loop so that it stays in that loop and other inputs aren't wiped out (and also make sure that the sum doesn't add those negative inputs)
int input = 0;
for (; input < exams; input++) {
int n = s.nextInt();
if (n>=0)
sum+=n;
else {
input--;
System.out.println("Invalid exam score entered, reenter: ");
}
}
EDIT: Use interactive input, which should be more user friendly.
You need to reset your loop counter to start the loop again:
// Delete first output and counter variable initialization before loop
for (int input = 1; input < exams; input++) {
System.out.println(String.format("Enter %d. exam score: ", input + 1));
int n = s.nextInt();
if (n < 0) {
System.out.println("Invalid value (must be positive)!");
input--; // Reenter last value
} else {
sum+=n; // Only use correct scores.
}
}

How do I find the lowest score entered using for loops [duplicate]

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;
}

Categories