I'm having issues getting this to run.
I can't manage to get the return value to work properly. I'm a few weeks into this course and I'm learning a lot but this project has been a little bit of a struggle for me.
I'm collecting data, creating an average and then using that average to output the corresponding letter grade.
Any help would be appreciated.
import java.util.*;
public class LetterGrade
{
public static void main(String args[])
{
calculateAvg();
double avgScore;
printLetter(double);
}
public static void calculateAvg()
{
Scanner console = new Scanner(System.in);
double avgScore;
for (double i = 0; i >0; i++)
{
System.out.println("Enter your full name.");
String name = console.nextLine();
System.out.println("Enter test score 1");
double score1 = console.nextDouble();
System.out.println("Enter test score 2");
double score2 = console.nextDouble();
System.out.println("Enter test score 3");
double score3 = console.nextDouble();
avgScore = (score1 + score2 + score3) / 3;
avgScore = console.nextInt();
System.out.printf( "%s, your average test score is: %.1f",name,avgScore);
return avgScore;
}
}
public static void printLetter(double avgScore)
{
Scanner console = new Scanner(System.in);
char grade;
if (avgScore >= 90)
{
grade = 'A';
}
else if (avgScore >= 80)
{
grade = 'B';
}
else if (avgScore >= 70)
{
grade = 'C';
}
else if (avgScore >= 60)
{
grade = 'D';
}
else
{
grade = 'F';
}
System.out.println("With that average, your grade is: " + grade);
}
}
There are several errors in your program.
I have corrected the program with comments:
import java.util.*;
public class LetterGrade
{
public static void main(String args[])
{
double avgScore= calculateAvg();
printLetter(avgScore); //pass variable name here not datatype
}
public static double calculateAvg() //must have return type
{
Scanner console = new Scanner(System.in);
double avgScore;
// for (double i = 0; i 0; i++)
//{
System.out.println("Enter your full name.");
String name = console.nextLine();
System.out.println("Enter test score 1");
double score1 = console.nextDouble();
System.out.println("Enter test score 2");
double score2 = console.nextDouble();
System.out.println("Enter test score 3");
double score3 = console.nextDouble();
avgScore = (score1 + score2 + score3) / 3;
// avgScore = console.nextInt();
System.out.printf( "%s, your average test score is: %.1f",name,avgScore);
return avgScore;
// }
}
public static void printLetter(double avgScore)
{
//Scanner console = new Scanner(System.in);
char grade;
if (avgScore >= 90)
{
grade = 'A';
}
else if (avgScore >= 80)
{
grade = 'B';
}
else if (avgScore >= 70)
{
grade = 'C';
}
else if (avgScore >= 60)
{
grade = 'D';
}
else
{
grade = 'F';
}
System.out.println("With that average, your grade is: " + grade);
}
}
OUTPUT:
Enter your full name.
manisha
Enter test score 1
12
Enter test score 2
14
Enter test score 3
15
manisha, your average test score is: 13.7With that average, your grade is: F
You made many mistakes.
In the main method you should save the calculated average into the variable and pass it to the printLetter method like this
double avgScore = calculateAvg();
printLetter(avgScore);
The calculateAvg method return type should be double so you have to declare it like this
public static double calculateAvg()
Also the for loop inside calculateAvg is wrong and unnecessary so just remove it. And assigning the scanner.nextInt() value to the avgScore will discard the properly calculated value. so the calculateAvg method should be like this
The printLetter method is correct but contains unnecessary lines like
Scanner console = new Scanner(System.in); //Could be removed
The resulting code is
import java.util.*;
public class LetterGrade
{
public static void main(String args[])
{
double avgScore = calculateAvg();
printLetter(avgScore);
}
public static double calculateAvg()
{
Scanner console = new Scanner(System.in);
double avgScore;
System.out.println("Enter your full name.");
String name = console.nextLine();
System.out.println("Enter test score 1");
double score1 = console.nextDouble();
System.out.println("Enter test score 2");
double score2 = console.nextDouble();
System.out.println("Enter test score 3");
double score3 = console.nextDouble();
avgScore = (score1 + score2 + score3) / 3;
System.out.printf( "%s, your average test score is: %.1f\n", name, avgScore);
return avgScore;
}
public static void printLetter(double avgScore)
{
char grade;
if (avgScore >= 90)
{
grade = 'A';
}
else if (avgScore >= 80)
{
grade = 'B';
}
else if (avgScore >= 70)
{
grade = 'C';
}
else if (avgScore >= 60)
{
grade = 'D';
}
else
{
grade = 'F';
}
System.out.println("With that average, your grade is: " + grade);
}
}
Checkout your main function. You have to assign the variable correctly to the return value of the calculateAvg method. Try this out:
public static void main(String args[]) {
double avgScore = calculateAvg();
printLetter(avgScore);
}
Also notice: double is the type of the variable, not the name. You have to give the name into the printLetter() method.
Another issue I just found is the doubled assigning of the avgScore variable which you have in your calculateAvg() method. Remove this line:
avgScore = console.nextInt();
This would force the user to again type in a value, which gets then assigned to the variable avgScore. This is not necessary.
Try to change the main method to this:
public static void main(String args[]) {
double avgScore = calculateAvg();
printLetter(avgScore);
}
There are some comments that I hope to be useful for you:
1- change the code in the main method to be like that
double avgScore = calculateAvg();
printLetter(avgScore);
2- check the use of the for loop (maybe you need a do while loop)
3- remove the scanner in "printLetter" method
4- also as #NiklasLehnfeld suggest to remove avgscore = console.nextInt();
Related
Java
How do I continue to loop until the user wants to quit? I have tried inserting a do while loop but no matter where I put it, it doesn't seem to work. it keeps giving me an error message. I want to loop this until the user doesn't want to enter a score anymore. so it will continue to prompt for another letter grade until they type a "Y" or "N". Thank you!
import java.util.Scanner;
public class gradeConverter {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int score = 0;
int minimum = 0;
int maximum = 100;
int grade = 0;
System.out.println("Enter letter grade 0-100: ");
score = scan.nextInt();
if (!isValidNumber(score,1,100))
{
System.exit(0);
}
getLetterGrade(score);
}
private static boolean isValidNumber(int number, int minimum, int maximum)
{
return number > minimum && number<=maximum;
}
private static String getLetterGrade(int score)
{
String grade=null;
if(score >=80 && score <90) {
System.out.println("B");//java code tells you that your letter grade is a B if you input a score that is between and includes 90 and 80
grade = "B";
}
else if(score <= 100 && score >= 90) {
System.out.println("A");//java code tells you that your letter grade is a A if you input a score that is between and includes 100 and 90
grade = "A";
}else if(60>score){
System.out.println("F");
grade = "F";
}
return grade;
}
}
You can simply use while loop until the user wants to quit. Add a condition on user prompt input and if the user tries to quit, just break the loop.
Also, you're exiting the system if the user gives invalid input. What you can do is, you can continue the program to make the user give a valid input.
while (true) {
System.out.println("Enter letter grade 0-100: ");
score = scan.nextInt();
if (!isValidNumber(score, minimum, maximum)) {
System.out.println("The input is not in valid range!");
continue;
}
letterGrade = getLetterGrade(score);
System.out.println("The corresponding letter grade is: " + letterGrade);
if (!doContinue(scan)) {
break;
}
}
The do continue function just checks whether the user wants to continue or not. Returns a boolean:
private static boolean doContinue(Scanner sc) {
System.out.println("Do you want to continue? (y/n): ");
String input = sc.next();
return input.toLowerCase().equals("y");
}
Also, instead of printing the grades while checking condition, you can just return it, just as I've done in the above segment:
private static String getLetterGrade(int score) {
if (score >= 80 && score < 90) {
return "B";
} else if (score >= 90 && score <= 100) {
return "A";
} else if (score < 60) {
return "F";
} else {
return "Unknown Grade";
}
}
And I guess you can change the min max range too, for a proper practical input:
private static boolean isValidNumber(int number, int minimum, int maximum) {
return number >= minimum && number <= maximum;
}
import java.util.Scanner;
public class gradeConverter {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
char opt;
int score = 0;
int minimum = 0;
int maximum = 100;
int grade = 0;
do {
System.out.println("Enter letter grade 0-100: ");
score = scan.nextInt();
if (!isValidNumber(score, 1, 100)) {
System.exit(0);
}
getLetterGrade(score);
System.out.println("Do yu wish to continue?: ");
opt = Character.toLowerCase(scan.next().charAt(0));
} while (opt == 'y');
}
private static boolean isValidNumber(int number, int minimum, int maximum) {
return number > minimum && number <= maximum;
}
private static String getLetterGrade(int score) {
String grade = null;
if (score >= 80 && score < 90) {
System.out.println("B");// java code tells you that your letter grade is a B if you input a score that
// is between and includes 90 and 80
grade = "B";
} else if (score <= 100 && score >= 90) {
System.out.println("A");// java code tells you that your letter grade is a A if you input a score that
// is between and includes 100 and 90
grade = "A";
} else if (60 > score) {
System.out.println("F");
grade = "F";
}
return grade;
}
}
The do ... while loop works for this but you might want to refactor your variable declarations to change with newer scores being inputted.
I refactored your code a bit, and added the possibility to say a grade or N in the same field.
I also added the possibility to loop until an incorrect value or a N value is typed, using a simple while condition
Just have a look and feel free to modify it again
import java.util.Scanner;
public class gradeConverter {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int minimum = 1;
int maximum = 100;
String grade;
boolean keep_going = true;
while(keep_going) {
System.out.println("Enter letter grade 0-100: ");
grade = scan.nextLine();
if (!isValidChoice(grade, minimum, maximum)) {
System.out.println("Invalid choice!");
keep_going = false;
break;
}
if(grade.toLowerCase().equals("n"))
keep_going = false;
else
getLetterGrade(Integer.parseInt(grade));
}
}
private static boolean isValidChoice(String value, int minimum, int maximum)
{
if(value.toLowerCase().equals("n"))
return true;
try {
int letter = Integer.parseInt(value);
return letter > minimum && letter<=maximum;
} catch (NumberFormatException e) {
return false;
}
}
private static String getLetterGrade(int score)
{
String grade=null;
if(score >=80 && score <90) {
System.out.println("B");//java code tells you that your letter grade is a B if you input a score that is between and includes 90 and 80
grade = "B";
}
else if(score <= 100 && score >= 90) {
System.out.println("A");//java code tells you that your letter grade is a A if you input a score that is between and includes 100 and 90
grade = "A";
}else if(60>score){
System.out.println("F");
grade = "F";
}
return grade;
}
}
You can scan in a loop and check the entered data for the need to exit it.
I also changed the type of the input value to support this check.
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String input;
int minimum = 0;
int maximum = 100;
int grade = 0;
System.out.println("Enter letter grade 0-100: ");
input = scan.nextLine();
while (!input.equals("y") || !input.equals("n")) {
int score = Integer.parseInt(input);
if (!isValidNumber(score,1,100)) {
getLetterGrade(score);
}
input = scan.nextLine();
}
System.exit(0);
}
I am new to java and having issues with my first project. I can't seem to get the variables in the correct scope and am unsure about the scanner methods. If anyone can help me with making it work it would be very helpful, thank you!
Create a new program called LetterGrade. Prompt the user to enter their name.
Create a method called calculateAvg(). Method should use a cumulative sum algorithm to prompt the user to enter 3 scores and calculate the average. Then, return that value to main.
Once the average is returned, Print the student's name and their average using printf() command. Create another method called printLetter(). Method should pass a parameter (average grade).
Use if … else if … else statements to print whether the student has an ‘A’, ‘B’, ‘C’, ‘D’, or ‘F’ average grade.
Grade Scale:
90-100 - A
80-89 - B
70-79 - C
60-69 - D
0-59 - F
Here is what I have so far:
import java.util.*;
public class LetterGrade {
private static Scanner console = new Scanner(System.in);
public static void main(String[] args) {
System.out.println("This program will calculate 3 scores to find the");
System.out.println("average score and letter grade.");
System.out.println();
Scanner console = new Scanner(System.in);
System.out.println("Enter your name: ");
String name = console.nextLine();
final double total = calculateAverage();
System.out.printf("Name: %s/nAverage: %f",name, total);
}
public static double calculateAverage() {
double sum = 0.0;
for (int i = 1; i <= 3; i++) {
System.out.print("Please enter score #" + i + ": ");
double next = console.nextDouble();
sum += next;
double total = (sum / 3);
return total;
}
return total;
}
public static double printLetter(int total) {
double total = console.nextDouble();
if (total < 60) {
System.out.print("You're grade is an F.");
} else if (total < 70) {
System.out.print("You're grade is a D.");
} else if (total < 80) {
System.out.print("You're grade is a C.");
} else if (total < 90) {
System.out.print("You're grade is a B.");
} else if (total <= 100) {
System.out.print("You're grade is an A.");
} else {
System.out.print("You have input an invalid number.");
}
}
}
public static double calculateAverage() {
double sum = 0.0;
for (int i = 0; i < 3; i++) {
System.out.print("Please enter score #" + (i+1) + ": ");
double next = console.nextDouble();
sum += next;
}
double total = (sum / 3);
return total;
}
public class LetterGrade{
private static Scanner console = new Scanner(System.in);
public static void main(String[] args) {
System.out.println("This program will calculate 3 scores to find the");
System.out.println("average score and letter grade.");
System.out.println();
System.out.println("Enter your name: ");
String name = console.nextLine();
final double total = calculateAverage();
System.out.printf("Name: %s/nAverage: %f",name, total);
printLetter(total);
}
public static double calculateAverage() {
double sum = 0.0;
double total = 0.0;
for (int i = 1; i <= 3; i++) {
System.out.print("Please enter score #" + i + ": ");
double next = console.nextDouble();
sum += next;
}
total = (sum / 3);
return total;
}
public static void printLetter(double total){
if (total < 60) {
System.out.print("You're grade is an F.");
}
else if (total < 70){
System.out.print("You're grade is a D.");
}
else if (total < 80){
System.out.print("You're grade is a C.");
}
else if (total < 90){
System.out.print("You're grade is a B.");
}
else if (total <= 100){
System.out.print("You're grade is an A.");
}
else{
System.out.print("You have input an invalid number.");
}
}
}
The immediate issue is that your for statement:
for (int i = 1; i <= 3; i++) {
System.out.print("Please enter score #" + i + "? ");
double next = console.nextDouble();
sum += next;
double total = (sum / 3);
return total;
}
does, not actually "loop" since you return during the very first iteration from it.
You probably want to move the last two lines where you calculate the total outside of it.
Other than that there were a few minor typos:
import java.util.Scanner;
class LetterGrade {
private static final int NUM_SCORES = 3;
public static void main(String[] args) {
System.out.printf("This program will calculate the average from %d scores and give you a letter grade.%n%n",
NUM_SCORES);
try (Scanner scanner = new Scanner(System.in)) {
System.out.print("Enter your name: ");
String name = scanner.nextLine();
double average = calculateAverage(scanner);
System.out.printf("%nReport:%n");
System.out.printf("Name: %s%nAverage: %.2f%n", name, average);
printLetterGrade(average);
}
}
private static double calculateAverage(Scanner scanner) {
double total = 0;
for (int i = 1; i <= NUM_SCORES; i++) {
double next = getDoubleInput(scanner, String.format("Please enter score #%d: ", i), 0, 100);
total += next;
}
return total / NUM_SCORES;
}
private static void printLetterGrade(double average) {
if (average < 60) {
System.out.println("Your grade is a F.");
} else if (average < 70) {
System.out.println("Your grade is a D.");
} else if (average < 80) {
System.out.println("Your grade is a C.");
} else if (average < 90) {
System.out.println("Your grade is a B.");
} else {
System.out.println("Your grade is an A.");
}
}
private static double getDoubleInput(Scanner scanner, String prompt, double minValue, double maxValue) {
System.out.print(prompt);
double validDouble = -1;
while (scanner.hasNext()) {
if (scanner.hasNextDouble()) {
validDouble = scanner.nextDouble();
if (validDouble >= minValue && validDouble <= maxValue) {
break;
} else {
System.out.printf("Error: Please enter a double between %.0f and %.0f inclusive%n", minValue,
maxValue);
System.out.print(prompt);
}
} else {
System.out.printf("Error: Please enter a double between %.0f and %.0f inclusive%n", minValue, maxValue);
System.out.print(prompt);
scanner.next();
}
}
return validDouble;
}
}
Example Usage:
This program will calculate the average from 3 scores and give you a letter grade.
Enter your name: Megan
Please enter score #1: -100
Error: Please enter a double between 0 and 100 inclusive
Please enter score #1: 105
Error: Please enter a double between 0 and 100 inclusive
Please enter score #1: 99
Please enter score #2: 98
Please enter score #3: 100
Report:
Name: Megan
Average: 99.00
Your grade is an A.
Try it out here.
this problem is with your foor loop which with every iteration it reset its value. you can also write much simple code as below:
public static double calculateAverage() {
double sum = 0.0;
for (int i = 1; i <= 3; i++) {
System.out.print("Please enter score #" + i + ": ");
sum += console.nextDouble();
}
return (sum / 3);
}
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 5 years ago.
Improve this question
Output Error :
Exception in thread "main" java.lang.RuntimeException: Uncompilable source code - illegal start of expression
I'm creating a class that calculate 1 student that take 3 quizzes 25%, 1 Midterm 25% , and 1 Final 50%
package Grading;
import java.util.Scanner;
public class Grading {
public static void main(String[] args) {
Scanner input =new Scanner(System.in);
public static double quiz1, quiz2, quiz3, midterm, finalExam, Grades, totalGrade, bothQuizzes, PfinalExam, PmidTerm;
public static String studentname;
public static int Score;
public String getstudentname( )
{
return studentname;
}
public double getquiz1()
{
return quiz1;
}
public double getquiz2 ()
{
return quiz2;
}
public double getquiz3 ()
{
return quiz3;
}
public double midterm()
{
return midterm;
}
public double finalExam()
{
return finalExam;
}
public void setquiz1 (double quiz1)
{
this.quiz1 = quiz1;
}
public void setquiz2 (double quiz2)
{
this.quiz2 = quiz2;
}
public void setquiz3 (double quiz3)
{
this.quiz3 = quiz3;
}
public void setmidterm()
{
this.midterm = midterm;
}
public void setfinalExam()
{
this.finalExam = finalExam;
}
public void setGrades ()
{
}
public String toString(){
return this.quiz1 + " " + this.quiz2 + this.quiz3 + " " + this.midterm + " " + this.finalExam;
}
public static void readInput(){
System.out.println("Please enter the grade you got for the first quiz: ");
quiz1 = grades.nextInt();
while (quiz1 <0 || quiz1>10)
{
System.out.println("Please enter a grade between zero and ten: ");
quiz1 = grades.nextInt();
}
System.out.println("Please enter the grade you got for the second quiz: ");
quiz2 = grades.nextInt();
while (quiz2 <0 || quiz2>10)
{
System.out.println("Please enter a grade between zero and ten: ");
quiz2 = grades.nextInt();
}
System.out.println("Please enter the grade you got for the third quiz: ");
quiz3 = grades.nextInt();
while (quiz3 <0 || quiz3>10)
{
System.out.println("Please enter a grade between zero and ten: ");
quiz3 = grades.nextInt();
}
System.out.println("Please enter the grade you got on your midterm: ");
midterm = grades.nextInt();
while (midterm <0 || midterm>100)
{
System.out.println("Please enter a grade between 0 and 100: ");
midterm = grades.nextInt();
}
System.out.println("Please enter the grade you got on your final exam: ");
finalExam = grades.nextInt();
while (finalExam < 0 || finalExam > 100)
{
System.out.println("Please enter a grade between 0 and 100: ");
finalExam = grades.nextInt();
}
}
public static void output()
{
System.out.println(" your score for the first quiz was " + quiz1 );
System.out.println("your score for the second quiz was " + quiz2);
System.out.println("your score for the third quiz was " + quiz3);
System.out.println(" your score for the midterm was " + midterm );
System.out.println("your score for the final exam was " + finalExam);
bothQuizzes = ((quiz1 + quiz2 + quiz3)/100)*.25;
PmidTerm = (midterm/100) *.35;
PfinalExam = (finalExam/100) * .40;
System.out.println("Your total grade for these grades is " + totalGrade + "%");
System.out.println("Your total grade for these grades is " + totalGrade);
double letterGrade = totalGrade;
if (letterGrade >= 90)
{
System.out.println("Your grade is an A");
// grade = "A";
}
else if (letterGrade >= 80)
{
System.out.println("Your grade is a B");
}
else if (letterGrade >= 70)
{
System.out.println("Your grade is a C");
}
else if (letterGrade >= 60)
{
System.out.println("Your grade is a D");
}
else
{
System.out.println("Your grade is an F");
}
}}
I have re-written your program. I hope that this is what you wanted to achieve. I didn't know how you wanted to count the grade, so I've marked the place where you can change that code with a comment.
Since there were some major problems in your code with field declaration and function bodies, I've reorganized them. You can take a look at this code:
import java.util.Scanner;
public class Grading {
private int quiz1, quiz2, quiz3, midterm, finalExam; //quizzes exams tests what grades
public void readInput () {
Scanner in = new Scanner(System.in);
System.out.print("Please enter the grade you got for the first quiz: ");
quiz1 = readInt(in, 0, 10);
System.out.print("Please enter the grade you got for the second quiz: ");
quiz2 = readInt(in, 0, 10);
System.out.print("Please enter the grade you got for the third quiz: ");
quiz3 = readInt(in, 0, 10);
System.out.print("Please enter the grade you got on your midterm: ");
midterm = readInt(in, 0, 100);
System.out.print("Please enter the grade you got on your final exam: ");
finalExam = readInt(in, 0, 100);
}
public void output () {
System.out.println("Your score for the first quiz was " + quiz1);
System.out.println("Your score for the second quiz was " + quiz2);
System.out.println("Your score for the third quiz was " + quiz3);
System.out.println("Your score for the midterm was " + midterm);
System.out.println("Your score for the final exam was " + finalExam);
//dunno if this is the way you want to count it; change as needed
double quizzes = (quiz1 + quiz2 + quiz3) / 100 * 0.25;
double Pmidterm = midterm / 100 * 0.25;
double PfinalExam = finalExam /100 * 0.50;
double totalGrade = (quizzes + Pmidterm + PfinalExam) * 100.0;
char grade;
if (totalGrade >= 90)
grade = 'A';
else if (totalGrade >= 80)
grade = 'B';
else if (totalGrade >= 70)
grade = 'C';
else if (totalGrade >= 60)
grade = 'D';
else grade = 'F';
System.out.printf("Your grade is %c\n", grade);
}
private int readInt (Scanner in, int min, int max) {
int value = in.nextInt();
if (value < min || value > max) {
System.out.printf("Please enter a grade between %d and %d: ", min, max);
return readInt(in, min, max);
}
return value;
}
public static void main(String[] args) {
Grading grading = new Grading();
grading.readInput();
grading.output();
}
}
You never closed your main function
I do not understand why my program will not allow me to convert my variable into char. Any help would be greatly appreciated!!! I am getting a total of 7 errors all either based around my test score grades or around the test score keyboard entry.
public class lab13
{
public static void main(String[] args)
{
// declare variables
int average;
int sum;
int i;
char grade;
int testScore;
//Create a Scanner Object
Scanner keyboard= new Scanner(System.in);
sum = 0;
i = 1;
while (i <= 4)
{
System.out.print("Enter a test score:");
testScore=keyboard.nextLine();
if (testScore < 60)
{
grade =(F);
}
else
{
if (testScore < 70)
{
grade =("D");
}
else
{
if (testScore < 80)
{
grade =("C");
}
else
{
if (testScore < 90)
{
grade =("B");
}
else
{
grade =("A");
}
}
}
}
System.out.print("Test score:"+testScore);
System.out.print("Letter grade:"+grade);
sum = sum + testScore;
i = i + 1;
}
average = sum / 4;
System.out.print("Test score average = " + average);
} // close main
} // close lab13
A char constant can be expressed with '' like
grade = 'F';
and
grade = 'D';
and
grade = 'C';
and
grade = 'B';
and
grade = 'A';
char can only hold a single character, which is defined using single quotes, as in 'C'
Insted of keyboard.nextLine() use keyboard.nextInt() and for character value assignment directly use character with single quota like 'A' instead of ("A")
import java.util.Scanner;
public class lab13
{
public static void main(String[] args)
{
// declare variables
int average;
int sum;
int i;
char grade;
int testScore;
//Create a Scanner Object
Scanner keyboard= new Scanner(System.in);
sum = 0;
i = 1;
while (i <= 4)
{
System.out.print("Enter a test score:");
testScore=keyboard.nextInt();
if (testScore < 60)
{
grade ='F';
}
else
{
if (testScore < 70)
{
grade ='D';
}
else
{
if (testScore < 80)
{
grade ='C';
}
else
{
if (testScore < 90)
{
grade ='B';
}
else
{
grade ='A';
}
}
}
}
System.out.println("Test score:"+testScore);
System.out.println("Letter grade:"+grade);
sum = sum + testScore;
i = i + 1;
}
average = sum / 4;
System.out.print("Test score average = " + average);
} // close main
} // close lab13
I'm writing a program that takes user input of five students and four test scores per student and puts them into arrays. It then averages the student's scores and gives a letter grade. The program also needs an input validation that doesn't accept scores under 0 and over 100.
So far my program validates the user and tells them that they've input an invalid number, but I would also like for it to prompt the user to start over after they've input an invalid number. I've tried a couple of different options as you will see below (in the enterData method), but none of which force the user to start over. Any suggestions?
import java.util.Scanner;
public class GradeBook {
private String[] names = new String[5];
private char[] grades = new char[5];
private double[] scores1 = new double[5];
private double[] scores2 = new double[5];
private double[] scores3 = new double[5];
private double[] scores4 = new double[5];
private double[] scores5 = new double[5];
int studentData = 0;
int studentCount = 0;
Scanner keyboard = new Scanner(System.in);
public void enterData() {
do {
System.out.println("Enter the student's name:");
String student = keyboard.nextLine();
System.out.println("Enter the student's first test score");
double score1 = Double.parseDouble(keyboard.nextLine());
if (score1 > 0 || score1 < 100) {
} else {
System.out.println("Invalid number");
continue;
}
System.out.println("Enter the student's second test score");
double score2 = Double.parseDouble(keyboard.nextLine());
if (score2 > 0 || score2 < 100) {
} else {
System.out.println("Invalid number");
System.out.println("Please start over");
continue;
}
System.out.println("Enter the student's third test score");
double score3 = Double.parseDouble(keyboard.nextLine());
if (score3 < 0 || score3 > 100)
System.out.println("Invalid number");
System.out.println("Enter the student's fourth test score");
double score4 = Double.parseDouble(keyboard.nextLine());
if (score4 < 0 || score4 > 100)
System.out.println("Invalid number");
addStudent(student, score1, score2, score3, score4);
studentData++;
} while (studentData < 5);
}
public String toString() {
StringBuilder printout = new StringBuilder();
for (int i = 0; i < names.length; i++) {
if (names[i] == null)
continue;
printout.append("Student name: " + names[i] + "\t" + "Average test score: " +
getAverage(i) + "\t" + "Grade: " + grades[i] + "\n");
}
return printout.toString();
}
private void addStudent(String inName, double scr1, double scr2, double scr3, double scr4) {
names[studentCount] = inName;
scores1[studentCount] = scr1;
scores2[studentCount] = scr2;
scores3[studentCount] = scr3;
scores4[studentCount] = scr4;
grades[studentCount] = getLetterGrade(studentCount);
studentCount++;
}
private double getAverage(int index) {
double score1 = scores1[index];
double score2 = scores2[index];
double score3 = scores3[index];
double score4 = scores4[index];
double average = (score1 + score2 + score3 + score4) / 4.0;
return average;
}
private char getLetterGrade(int index) {
double average = getAverage(index);
char grade;
if (average >= 90)
grade = 'A';
else if (average >= 80)
grade = 'B';
else if (average >= 70)
grade = 'C';
else if (average >= 60)
grade = 'D';
else
grade = 'F';
return grade;
}
}
I made this more difficult than needed. This works just fine.
System.out.println("Enter the student's third test score");
double score3 = Double.parseDouble(keyboard.nextLine());
while (score3 < 0 || score3 > 100)
{
System.out.println("Invalid score, plese reenter");
System.out.println("Enter the student's third test score");
score3 = Double.parseDouble(keyboard.nextLine());
}
Well I know of a way to do this using JOptionPanes:
int n = JOptionPane.showConfirmDialog(null,
"Would you like to start over?",
"Incorrect Input",
JOptionPane.YES_NO_OPTION);
if(n == JOptionPane.YES_OPTION)
{
//start over
}
else
{
System.exit(0);
}
I guess whatever the equivalent this would be in the System class.
What you want to do is flow control. The easiest ways are:
1) Make your method return a boolean. If the method exits correctly (all data entered) return true, if the method has to exit in error (as in this case), return false (in this case, from inside the if that controls the condition.
2) Throw an exception if the method finds an error.
In both cases, the logic calling your method will have to check for the return value/exception thrown and call again the method if it is needed.
System.out.println("Enter the student's third test score");
double score3 = Double.parseDouble(keyboard.nextLine());
while (score3 < 0 || score3 > 100)
{
System.out.println("Invalid score, plese reenter");
System.out.println("Enter the student's third test score");
score3 = Double.parseDouble(keyboard.nextLine());
}