Reputation: 45
I have a program that allows the user to select from 4 choices: 1 - Set percentage for grades 2 - Enter grades 3 - Get average 4 - Quit
The program is working smoothly, no compile errors, and I am able to choose each choice and get the line of text to display properly.
My question is, when users select choice 2 to enter grades, how can they enter more than 1 grade without it executing? Currently when you type in a grade, press enter, it will bring you back to the main menu without allowing you to enter more than 1 grade. Here is the code:
import java.util.Scanner;
public class ExerciseThree
{
public static void main ( String[] argsv )
{
float percent = 0;
double grade = 0;
double totalAvg = 0;
double total = 0;
double gradeAvg = 0;
int gradeCounter = 0;
int quit;
int choice = 0;
Scanner input = new Scanner (System.in);
while (choice != 4 )
{
System.out.println( "Please choose one of the following: \n 1 - Set percentage of total for new grades \n 2 - Enter new grades \n 3 - Get average \n 4 - Quit ");
choice = input.nextInt();
switch (choice)
{
case 1:
System.out.println( "Enter a percentage to multiply by (Format: 10% = .10)" );
percent = input.nextFloat();
break;
case 2:
System.out.println( "Enter grades" );
grade = input.nextDouble();
total = total + grade;
gradeCounter = gradeCounter + 1;
gradeAvg = (double) total / gradeCounter;
break;
case 3:
System.out.println( "You have chosen to get the average" );
totalAvg = totalAvg + percent * grade;
totalAvg = input.nextDouble();
break;
default:
System.out.println( "You have chosen to quit" );
break;
}
}
}
}
Upvotes: 0
Views: 134
Reputation: 2296
System.out.print("How Many Grades You Enter");
int s=input.nextInt();
while(s>0)
{
System.out.println( "Enter grades" );
grade = input.nextDouble();
total = total + grade;
gradeCounter = gradeCounter + 1;
gradeAvg = (double) total / gradeCounter;
s--;
}
Upvotes: 1
Reputation: 394
How about a while loop in the case-block?
while (gradCounter < 4) {
System.out.println( "Enter grades" );
grade = input.nextDouble();
total = total + grade;
gradeCounter = gradeCounter + 1;
gradeAvg = (double) total / gradeCounter;
}
Upvotes: 0
Reputation: 391
Make a loop until they enter a stop character (for example a blank character)
case 2:
System.out.println( "Enter grades" );
boolean isDone = false;
while(isDone == false) {
grade = input.nextDouble();
if(grade == '') {
isDone = true;
}
}
total = total + grade;
gradeCounter = gradeCounter + 1;
gradeAvg = (double) total / gradeCounter;
Upvotes: 1