java - break loop with invalid input - java

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

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)

Having Trouble with Correct output from If statement [closed]

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'? :)

Java Loops are kicking my butt

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.

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.

Why does my code not run?

I have this code:
import java.util.Scanner;
public class PositiveNegative { public static void main(String[] args) {
int numbers, plus = 0, minus = 0;
int count = 0;
double total = 0;
Scanner scan = new Scanner(System.in);
System.out.print("Enter an integer (0 to quit): ");
numbers = scan.nextInt();
while(numbers != 0)
{
total += numbers;
if(numbers > 0)
plus++;
if(numbers < 0)
minus++;
}
System.out.println("The number of positives is: " +plus);
System.out.println("The number of negatives is: " +minus);
System.out.println("The number of total is: " +total);
}
}
The problem with is that I try to run it and type the numbers but it does nothing. I want it so that when you type 0 it stops taking numbers and starts processing the code. What should I do?
Try this:
import java.util.Scanner;
public class PositiveNegative {
public static void main(String[] args) {
int numbers = 0, plus = 0, minus = 0;
double total = 0;
do{
Scanner scan = new Scanner(System.in);
System.out.print("Enter an integer (0 to quit): ");
numbers = Integer.valueOf(scan.nextLine());
total += numbers;
if (numbers > 0)
plus++;
if (numbers < 0)
minus++;
}
while (numbers != 0);
System.out.println("The number of positives is: " + plus);
System.out.println("The number of negatives is: " + minus);
System.out.println("The number of total is: " + total);
}
}
Put your Scanner in the while loop so that everytime loop start it will ask for User input.
You need to update numbers or your loop will run for ever. And I recommend using braces (and an else). Something like,
System.out.print("Enter an integer (0 to quit): ");
numbers = scan.nextInt();
while (numbers != 0) {
total += numbers;
if (numbers > 0) {
plus++;
} else if (numbers < 0) {
minus++;
}
System.out.print("Enter an integer (0 to quit): ");
numbers = scan.nextInt();
}
Alternatively, you could use a do-while loop. Then you only need one copy of the prompt. Like,
do {
System.out.print("Enter an integer (0 to quit): ");
numbers = scan.nextInt();
total += numbers;
if (numbers > 0) {
plus++;
} else if (numbers < 0) {
minus++;
}
} while (numbers != 0);
You have to modify numbers each time to make it work in your while.
So, in your existing code, just comment out numbers = scan.nextInt(); and use below--
// numbers = scan.nextInt(); //comment out this call
while ((numbers = scan.nextInt()) != 0) {
....
this will give you desired output--
Enter an integer (0 to quit): 9
4
-9
1
0
The number of positives is: 3
The number of negatives is: 1
The number of total is: 5.0

Categories