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());
}
Related
I have an application that acts as a gradebook. However, in the console log when I type in a grade there seems to be an error. I was hoping someone could fix this to where I am able to put in a grade percentage and the error does not pop up.enter code here
Below is what the error says:java.lang.NumberFormatException: For input string: "70%"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:580)
at java.lang.Integer.parseInt(Integer.java:615)
at Gradebook.getScores(Gradebook.java:45)
at Gradebook.main(Gradebook.java:154)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at edu.rice.cs.drjava.model.compiler.JavacCompiler.runCommand(JavacCompiler.java:272)
Here is my code:
import java.util.Scanner;
public class Gradebook {
//getNumStudents takes a Scanner object as parameter
//the reader object lets us take user input
public static int getNumStudents(Scanner reader){
int numStudents = 0;
//we get the number of students
do{
System.out.print("Enter number of students: ");
numStudents = Integer.parseInt(reader.nextLine());
//we determine if the user input is valid
//it should be greater than 0
//because we don't want the number o students to be negative
//if it is not valid then we keep taking inputs
if(numStudents > 0){
break;
}else{
System.out.println("Please enter atleast 1 student.");
}
}while(true);
System.out.println("================================================================================================================================================");
//we return numStudents
return numStudents;
}
//getScores takes our Scanner object again and the number student as parameter this time
public static String[] getScores(Scanner reader, int numStudents){
//we create an array of string studInfo
//that will be returned containing the name, and scores of our students
String[] studInfo = new String[numStudents];
String name = "";
int quiz = 0;
int assign = 0;
int test1 = 0;
int test2 = 0;
//we use a for loop to keep taking student scores
for(int i = 0; i < numStudents; i++){
//enter name
System.out.print("Enter student "+(i+1)+" name: ");
name = reader.nextLine();
//enter quiz, assignment, test1 and test2 scores
//we also validate scores to not be negative
//and not out of bounds
do{
System.out.print("Enter Quiz Score (over 40): ");
quiz = Integer.parseInt(reader.nextLine());
if(quiz >= 0 && quiz <= 40){
break;
}else{
System.out.println("Please put a valid score.");
}
}while(true);
do{
System.out.print("Enter Assignment Score (over 30): ");
assign = Integer.parseInt(reader.nextLine());
if(assign >= 0 && assign <= 30){
break;
}else{
System.out.println("Please put a valid score.");
}
}while(true);
do{
System.out.print("Enter Midterm Test Score (over 55): ");
test1 = Integer.parseInt(reader.nextLine());
if(test1 >= 0 && test1 <= 55){
break;
}else{
System.out.println("Please put a valid score.");
}
}while(true);
do{
System.out.print("Enter Final Test Score (over 65): ");
test2 = Integer.parseInt(reader.nextLine());
if(test2 >= 0 && test2 <= 65){
break;
}else{
System.out.println("Please put a valid score.");
}
}while(true);
//after we get the name and student's score
//we put it in a string
studInfo[i] = name+ " " +quiz+ " " +assign+ " " +test1+ " " +test2;
System.out.println();
}
//return the studInfo
return studInfo;
}
//our displayGrade takes String array as parameter
public static void displayGrade(String[] studInfo){
//this is our header for our formatted table
System.out.println("================================================================================================================================================");
System.out.println(String.format("%-30s%-10s%-12s%-15s%-12s%-10s%-15s%s", "Name", "Quiz", "Assignment", "Midterm Test", "Final Test", "Average", "Letter Grade", "Status"));
System.out.println("================================================================================================================================================");
//we go through our array of string
for(int i = 0; i < studInfo.length; i++){
//the split method returns an array of strings
//that are split by a delimeter
String[] data = studInfo[i].split(" ");
//we sum up the scores
//but we have to parse it to double first
//to get the closest sum
double sum = ((Double.parseDouble(data[1]) / 40.0) * 100.0) * 0.15;
sum += ((Double.parseDouble(data[2]) / 30.0) * 100.0) * 0.15;
sum += ((Double.parseDouble(data[3]) / 55.0) * 100.0) * 0.3;
sum += ((Double.parseDouble(data[4]) / 65.0) * 100.0) * 0.4;
//after that we round the sum and convert it to int and put it in average
int average = (int) Math.round(sum);
char letterGrade = ' ';
//we get the letter grade using a nested if else
if(average>=0 && average<=59){
letterGrade = 'F';
}else if(average>=60 && average<=69){
letterGrade = 'D';
}else if(average>=70 && average<=79){
letterGrade = 'C';
}else if(average>=80 && average<=89){
letterGrade = 'B';
}else if(average>=90 && average<=100){
letterGrade = 'A';
}
String status = "";
//we determine the status of our student here
//using switch case
//if the leter grade is f then he fails
//if the case is D then he needs to go to remedial class
//otherwise they pass
switch(letterGrade){
case 'F':
status = "Fail";
break;
case 'D':
status = "Remedial";
break;
case 'A': case 'B': case 'C':
status = "Pass";
break;
}
//we displat student information
System.out.println(String.format("%-30s%-10s%-12s%-15s%-12s%-10d%-15c%s", data[0], data[1], data[2], data[3], data[4], average, letterGrade, status));
}
System.out.println("================================================================================================================================================");
}
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
displayGrade(getScores(reader, getNumStudents(reader)));
}
}
Instead of nextLine() you can use next("[0-9]+%?") and then remove the optional % character:
public static int getNumStudents(Scanner reader) {
int numStudents = 0;
//we get the number of students
do {
System.out.print("Enter number of students: ");
// Read the number either with or without the % sign
String input = reader.next("[0-9]+%?");
if (input.endsWith("%")) {
// Remove the % sign if present
input = input.substring(0, input.length() - 1);
}
numStudents = Integer.parseInt(input);
// we determine if the user input is valid
// it should be greater than 0
// because we don't want the number o students to be negative
// if it is not valid then we keep taking inputs
if (numStudents > 0) {
break;
}
System.out.println("Please enter at least 1 student.");
} while (true);
System.out.println("================================================================================================================================================");
// we return numStudents
return numStudents;
}
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);
}
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();
When the final grade is above 200, i want an error message to show up but it doesn't, i tried to structure my loop that way but it just doesnt work.
import java.util.Scanner;
import java.util.Formatter;
public class Lab3 {
public static void main(String[] args) {
double midtermGrade = 50.0;
double homeworkGrade = 0.0;
double finalExamGrade = 50.0;
double finalGrade = 0.0;
char letterGrade = ' ';
Scanner scan = new Scanner(System.in);
System.out.println("Enter homework grade: ");
homeworkGrade = scan.nextDouble();
System.out.println("Enter midterm exam grade: ");
midtermGrade = scan.nextDouble();
System.out.println("Enter final exam grade: ");
finalExamGrade = scan.nextDouble();
if ((!(homeworkGrade >= 0) || !(homeworkGrade <= 100))) return;
if (((midtermGrade >= 0) && (midtermGrade <= 100)))
if ((((!(finalExamGrade > 0) || !(finalExamGrade < 200))))) {
finalGrade = (finalExamGrade / 200) * 50 + (midtermGrade * .25) + (homeworkGrade * .25); //.25 denotes 25%
}
System.out.println("Invalid input. Homework and midterm grades should be between 0 and 100 and the final grade should be between 0 and 200");
if (finalGrade >= 50) {
letterGrade = 'P';
} else if (finalGrade < 50) {
letterGrade = 'F';
}
if (letterGrade == 'P') {
System.out.println("Student passed the class");
} else if (letterGrade == 'F') {
System.out.println("Student failed the class");
}
}
}
When i put the obnoxiously large numbers, i don't get any message. The debug ends.
I think the ! is interfering with the final grade
i change your code and now it works. here it is:
package test;
import java.util.Scanner;
public class Testing {
public static void main(String[] args) {
double midtermGrade = 50.0;
double homeworkGrade = 0.0;
double finalExamGrade = 50.0;
double finalGrade = 0.0;
char letterGrade = ' ';
Scanner scan = new Scanner(System.in);
System.out.println("Enter homework grade: ");
homeworkGrade = scan.nextDouble();
if (!(homeworkGrade >= 0) || !(homeworkGrade <= 100)) {
System.out.println("Invalid input.Homework grades should be between 0 and 100");
return;
}
System.out.println("Enter midterm exam grade: ");
midtermGrade = scan.nextDouble();
if (!(midtermGrade >= 0) && !(midtermGrade <= 100)){
System.out.println("Invalid input.midterm grades should be between 0 and 100");
return;
}
System.out.println("Enter final exam grade: ");
finalExamGrade = scan.nextDouble();
if ((!(finalExamGrade > 0) || !(finalExamGrade < 200))) {
System.out.println("Invalid input. final grade should be between 0 and 200");
return;
}
finalGrade = (finalExamGrade / 200) * 50 + (midtermGrade * .25) + (homeworkGrade * .25); //.25 denotes 25%
if (finalGrade >= 50) {
letterGrade = 'P';
} else if (finalGrade < 50) {
letterGrade = 'F';
}
if (letterGrade == 'P') {
System.out.println("Student passed the class");
} else if (letterGrade == 'F') {
System.out.println("Student failed the class");
}
}
}
You just need to change your package name and class name.
Note:
- its better to check each input, after the scan. And check if the value is right or not. if the input data is not right, you should return and terminate the program.
I'm a new Java student(self studying at home), and I made this average calculator which works perfect, but I wanted to add a condition that prevents the user from typing in a number bigger then 100, because grades usually end at 100, I'm struggling a bit on what is the right way of doing so.
Here is my code:
import java.util.Scanner;
class books{
public static void main(String args[]){
Scanner userInput = new Scanner(System.in);
int total = 0;
int grade = 0;
int average;
int counter = 0;
System.out.println("Please enter all your grades:");
while(counter < 12){
grade = userInput.nextInt();
total = total + grade;
counter++;
if(grade > 100){
System.out.println("Please enter a valid grade");
}
}
average = total/12;
System.out.println("You average is " + average);
}
}
Thanks.
Before using the entered grade value, you should validate it and if it's not valid, to continue with the loop:
while(counter < 12){
grade = userInput.nextInt();
if (grade > 100) {
System.out.println("Please enter a valid grade");
} else {
total = total + grade;
counter++;
}
}
Also, when calculating the average of multiple values, it's not that good idea to do integer division, because you can get wrong results. Better do:
double average = 0d;
...
average = total / 12.0;
The solution is:
import java.util.Scanner;
class books{
public static void main(String args[]){
Scanner userInput = new Scanner(System.in);
int total = 0;
int grade = 0;
int average;
int counter = 0;
System.out.println("Please enter all your grades:");
while(counter < 12){
grade = userInput.nextInt();
if(grade > 100 || grade < 0){
System.out.println("Please enter a valid grade again!");
}else{
total = total + grade;
counter++;
}
}
average = total/12;
System.out.println("You average is " + average);
}
}
Credit goes to Kocko ;)