Local variable may not be initialized - java

I'm trying to make a grade calculator. Everything is working to specifications except the program is not handling the conditionals correctly to output the right letter grade.
Any help on this?
import java.util.Scanner;
public class GradeCalculator {
public static void main(String args []) {
String name;
String major;
int attendance;
int homework;
int project1;
int project2;
int midterm;
int finalexam;
int extra;
String finalgrade;
double attweight = 0.05;
double hwweight = 0.35;
double project1weight = 0.075;
double project2weight = 0.075;
double midtermweight = 0.20;
double finalweight = 0.25;
double totalgrade;
Scanner in = new Scanner(System.in);
System.out.println("What is your name? ");
name = in.nextLine();
System.out.println("What is your major? ");
major = in.nextLine();
System.out.println("What is your attendance grade (out of 100)? ");
attendance = in.nextInt();
System.out.println("What is your homework grade (out of 100)? ");
homework = in.nextInt();
System.out.println("What is your project 1 grade? ");
project1 = in.nextInt();
System.out.println("What is your project 2 grade? ");
project2 = in.nextInt();
System.out.println("What is your midterm grade? ");
midterm = in.nextInt();
System.out.println("What is your final grade? ");
finalexam = in.nextInt();
if(attendance > 100 || homework > 100 || project1 > 100 || project2 >100 || midterm > 100 || finalexam > 100) {
System.out.println("Your grade cannot exceed 100");
}
totalgrade = ((attendance * attweight) + (homework * hwweight) + (project1 * project1weight) + (project2 * project2weight) + (midterm * midtermweight) + (finalexam * finalweight));
if(totalgrade > 93 && totalgrade < 100){
finalgrade = "A";
}
if(totalgrade > 89 && totalgrade < 93){
finalgrade = "A-";
}
if(totalgrade > 86 && totalgrade < 90){
finalgrade = "B+";
}
if(totalgrade > 82 && totalgrade < 87){
finalgrade = "B";
}
if(totalgrade > 79 && totalgrade < 83){
finalgrade = "B-";
}
if(totalgrade > 76 && totalgrade < 80){
finalgrade = "C+";
}
if(totalgrade > 72 && totalgrade < 77){
finalgrade = "C";
}
if(totalgrade > 69 && totalgrade < 73){
finalgrade = "C-";
}
if(totalgrade > 59 && totalgrade < 70){
finalgrade = "D";
}
if(totalgrade < 60){
finalgrade = "F";
}
System.out.println("Your name is " + name + " and your major is " + major + ". Your attendance grade is " + attendance + ", your homework grade is " + homework + ", your project one grade is " + project1 + ", your project two grade is " + project2 + ", your midterm grade is " + midterm + ", your final exam grade is" + finalexam + ". Your total grade is " + totalgrade + " and your letter grade is " + finalgrade);
}
}
Error:
The local variable finalgrade may not have been initialized

EDIT: Elaboration
You already told us the problem. You need to initialize finalgrade. You did initialize it inside your conditional statements, however this is not guaranteed to happen when try to read the variable's value in your output (because the initialization only happens if you satisfy a condition) so the compiler gets mad. An easy work around would be to start out setting finalgrade to the empty string.
String finalgrade = "";
Also, look at your conditional statements. You're excluding 93, maybe other numbers. It would be better to use 'else if', after the first 'if' statement.

Related

Java -vending machine that can't accept pennies

So I'm working on a java project that involves creating a soda machine that adjusts price based on temperature. I can't seem to figure out how to make sure the machine does NOT accept pennies when accepting payment from the user.
I feel like I'm overcoding but I'm at my wit's end because I don't have any clue how to not accept pennies.
import java.util.*;
import java.text.*;
public class SodaMachine extends SodaTester
{
public static void main(String[] args)
{
double temp;
double money;
double change;
double price1 = .50;
double price2 = .55;
double price3 = .60;
double price4 = .65;
double price5 = .75;
double price6 = .80;
double price7 = .85;
double price8 = .90;
double price9 = 1.00;
System.out.println("Hi there! Please enter the temperature in Farenheit:");
Scanner scan = new Scanner(System.in);
temp = scan.nextDouble();
DecimalFormat fmt = new DecimalFormat("0.#");
NumberFormat fmt2 = NumberFormat.getCurrencyInstance();
if (temp < 40 || temp > 120)
{
System.out.println("Invalid input. Temperature should be between 40 and 120 degrees Farenheit.");
while (temp < 40 || temp > 120)
{
temp = scan.nextDouble();
System.out.println("The rounded temperature in degrees Farenheit is: " + fmt.format(temp));
System.out.println("Invalid input. Temperature should be between 40 and 120 degrees Farenheit.");
}
}
if(temp < 50 && temp >= 40)
{
System.out.println("The rounded temperature in degrees Farenheit is: " + fmt.format(temp));
System.out.println("The price is: " + fmt2.format(price1));
System.out.println("Please insert amount of payment: ");
money = scan.nextDouble();
while (money < price1)
{
System.out.println("Invalid input please try again. Your total is: " + fmt2.format(price1));
money = scan.nextDouble();
}
change = money - price1;
System.out.println("Your Change is: " + fmt2.format(change));
}else if (temp >= 50 && temp <= 60) {
System.out.println("The rounded temperature in degrees Farenheit is: " + fmt.format(temp));
System.out.println("The price is: " + fmt2.format(price2));
System.out.println("Please insert amount of payment: ");
money = scan.nextDouble();
while (money < price2)
{
System.out.println("Invalid input please try again. Your total is: " + fmt2.format(price2));
money = scan.nextDouble();
}
change = money - price2;
System.out.println("Your Change is: " + fmt2.format(change));
}else if (temp > 60 && temp <= 65) {
System.out.println("The rounded temperature in degrees Farenheit is: " + fmt.format(temp));
System.out.println("The price is: " + fmt2.format(price3));
System.out.println("Please insert amount of payment: ");
money = scan.nextDouble();
while (money < price3)
{
System.out.println("Invalid input please try again. Your total is: " + fmt2.format(price3));
money = scan.nextDouble();
}
change = money - price3;
System.out.println("Your Change is: " + fmt2.format(change));
}else if (temp > 65 && temp <= 70) {
System.out.println("The rounded temperature in degrees Farenheit is: " + fmt.format(temp));
System.out.println("The price is: " + fmt2.format(price4));
System.out.println("Please insert amount of payment: ");
money = scan.nextDouble();
while (money < price4)
{
System.out.println("Invalid input please try again. Your total is: " + fmt2.format(price4));
money = scan.nextDouble();
}
change = money - price4;
System.out.println("Your Change is: " + fmt2.format(change));
}else if (temp > 70 && temp <= 75) {
System.out.println("The rounded temperature in degrees Farenheit is: " + fmt.format(temp));
System.out.println("The price is: " + fmt2.format(price5));
System.out.println("Please insert amount of payment: ");
money = scan.nextDouble();
while (money < price5)
{
System.out.println("Invalid input please try again. Your total is: " + fmt2.format(price5));
money = scan.nextDouble();
}
change = money - price5;
System.out.println("Your Change is: " + fmt2.format(change));
}else if (temp > 75 && temp <= 80) {
System.out.println("The rounded temperature in degrees Farenheit is: " + fmt.format(temp));
System.out.println("The price is: " + fmt2.format(price6));
System.out.println("Please insert amount of payment: ");
money = scan.nextDouble();
while (money < price6)
{
System.out.println("Invalid input please try again. Your total is: " + fmt2.format(price6));
money = scan.nextDouble();
}
change = money - price6;
System.out.println("Your Change is: " + fmt2.format(change));
}else if (temp > 80 && temp <= 85) {
System.out.println("The rounded temperature in degrees Farenheit is: " + fmt.format(temp));
System.out.println("The price is: " + fmt2.format(price7));
System.out.println("Please insert amount of payment: ");
money = scan.nextDouble();
while (money < price7)
{
System.out.println("Invalid input please try again. Your total is: " + fmt2.format(price7));
money = scan.nextDouble();
}
change = money - price7;
System.out.println("Your Change is: " + fmt2.format(change));
}else if (temp > 85 && temp <= 90) {
System.out.println("The rounded temperature in degrees Farenheit is: " + fmt.format(temp));
System.out.println("The price is: " + fmt2.format(price8));
System.out.println("Please insert amount of payment: ");
money = scan.nextDouble();
while (money < price8)
{
System.out.println("Invalid input please try again. Your total is: " + fmt2.format(price8));
money = scan.nextDouble();
}
change = money - price8;
System.out.println("Your Change is: " + fmt2.format(change));
}else if (temp > 90 && temp <= 120) {
System.out.println("The rounded temperature in degrees Farenheit is: " + fmt.format(temp));
System.out.println("The price is: " + fmt2.format(price9));
System.out.println("Please insert amount of payment: ");
money = scan.nextDouble();
while (money < price9)
{
System.out.println("Invalid input please try again. Your total is: " + fmt2.format(price9));
money = scan.nextDouble();
}
change = money - price9;
System.out.println("Your Change is: " + fmt2.format(change));
}
}
}
I won't go into detail about your current code, but you basically want to check if the decimal value you've read from the user modulo-0.05 equals 0 (so it has no remainder). One issue in this is that floating point precision can interfere with the checks when you use double, which is why you'd always want to use java.math.BigDecimal for currency calculations.
Here an example:
BigDecimal input = new BigDecimal(scanner.next());
if(input.remainder(new BigDecimal("0.05")).compareTo(BigDecimal.ZERO) == 0){
System.out.println("Input "+input+" is valid!");
} else{
System.out.println("Input "+input+" is not valid!");
}
For the inputs "1", "1.00", "1.05", "4.35", "1.01", "3.21", "4.68" it will output the following:
Input 1 is valid!
Input 1.00 is valid!
Input 1.05 is valid!
Input 4.35 is valid!
Input 1.01 is not valid!
Input 3.21 is not valid!
Input 4.68 is not valid!
Try it online.
Since BigDecimal can be quite confusing for new Java users, you could perhaps let the user input the amount in cents (so as integers), in which case it can be something like this instead:
int input = scanner.nextInt();
if(input % 5 == 0){
System.out.println("Input "+input+" is valid!");
} else{
System.out.println("Input "+input+" is not valid!");
}
For the input "100", "105", "435", "101", "321", "468" it will output the following:
Input 100 is valid!
Input 105 is valid!
Input 435 is valid!
Input 101 is not valid!
Input 321 is not valid!
Input 468 is not valid!
Try it online.
EDIT: Since I had some time, I reworked your solution with re-usable methods.
Please have a good look what I did, and if you have any questions about specific parts let me know. It now uses recursive methods until the user enters a valid input. The boolean showMessage parameters in the methods are to show the "Please enter X" messages only once.
import java.lang.IllegalArgumentException;
import java.lang.NumberFormatException;
import java.math.BigDecimal;
import java.text.NumberFormat;
import java.util.InputMismatchException;
import java.util.Scanner;
public class SodaMachine{
private static final String currencySymbol = "$";
private static final BigDecimal roundOn = new BigDecimal("0.05");
private Scanner scanner;
private NumberFormat currencyFormat;
public SodaMachine(){
scanner = new Scanner(System.in);
currencyFormat = NumberFormat.getCurrencyInstance();
}
public static void main(String[] args){
SodaMachine sodaMachine = new SodaMachine();
double farenheitInput = sodaMachine.enterFarenheit(true);
System.out.println("The temperature in degrees Farenheit you've entered is: " + farenheitInput);
BigDecimal price = sodaMachine.determinePrice(farenheitInput);
System.out.println("The price is: " + sodaMachine.currencyFormat.format(price));
BigDecimal payment = sodaMachine.enterPayment(price, true);
BigDecimal change = payment.subtract(price);
System.out.println("Your change is: " + sodaMachine.currencyFormat.format(change));
}
private double enterFarenheit(boolean showMessage){
if(showMessage){
System.out.println("Hi there! Please enter the temperature in Farenheit:");
}
double farenheitInput;
try{
farenheitInput = scanner.nextDouble();
} catch(InputMismatchException ex){
scanner.nextLine(); // Get rid of the invalid user-input
System.out.println("The value you've entered is not a valid. The input should be a decimal input. Please try again.");
return enterFarenheit(false);
}
if(farenheitInput < 40 | farenheitInput > 120){
System.out.println("Invalid input. Temperature should be between 40 and 120 degrees Farenheit.");
return enterFarenheit(false);
}
return farenheitInput;
}
private BigDecimal determinePrice(double farenheit){
String strPrice;
// Temperature is in the range [40, 50):
if(farenheit >= 40 && farenheit < 50){
strPrice = "0.50";
}
// Temperature is in the range [50, 60]:
else if(farenheit >= 50 && farenheit <=60){
strPrice = "0.55";
}
// Temperature is in the range (60, 65]:
else if(farenheit > 60 && farenheit <= 65){
strPrice = "0.60";
}
// Temperature is in the range (65, 70]:
else if(farenheit > 65 && farenheit <= 70){
strPrice = "0.65";
}
// Temperature is in the range (70, 75]:
else if(farenheit > 70 && farenheit <= 75){
strPrice = "0.75";
}
// Temperature is in the range (75, 80]:
else if(farenheit > 75 && farenheit <= 80){
strPrice = "0.80";
}
// Temperature is in the range (80, 85]:
else if(farenheit > 80 && farenheit <= 85){
strPrice = "0.85";
}
// Temperature is in the range (85, 90]:
else if(farenheit > 85 && farenheit <= 90){
strPrice = "0.90";
}
// Temperature is in the range (90, 120]:
else if(farenheit > 90 && farenheit <= 120){
strPrice = "1.00";
}
// Invalid temperature range:
else{
// Since we already validated the input-range, it should never go here,
// but added it just in case.
throw new IllegalArgumentException("The temperature must be in the range [40, 120]!");
}
return new BigDecimal(strPrice);
}
private BigDecimal enterPayment(BigDecimal price, boolean showMessage){
if(showMessage){
System.out.println("Please enter amount of payment: ");
}
String userInput = scanner.next();
// Remove the optional currency symbol from the user input
userInput = userInput.replace(currencySymbol, "");
BigDecimal paymentInput;
try{
paymentInput = new BigDecimal(userInput);
} catch(NumberFormatException ex){
scanner.nextLine(); // Get rid of the invalid user-input
System.out.println("The value you've entered is not a valid. The input should be a price input. Please try again.");
return enterPayment(price, false);
}
if(paymentInput.compareTo(price) < 0){
System.out.println("Your payment of " + currencyFormat.format(paymentInput) + " is too low. Please try again. The total price is: " + currencyFormat.format(price));
return enterPayment(price, false);
}
if(paymentInput.remainder(roundOn).compareTo(BigDecimal.ZERO) != 0){
System.out.println("Your payment should be rounded to " + currencyFormat.format(roundOn) + ". Please try again.");
return enterPayment(price, false);
}
return paymentInput;
}
}
Try it online.
Your code can be simplified alot, but I will focus on the issue at hand.
I would create a function to get user input, ensuring it does not contain pennies:
double getMoney(String prompt, Scanner scan)
{
double money = 0;
while(true) { // Loop until proper input
System.out.println(prompt);
money = scan.nextDouble();
// There are a few ways to determine if it has pennies.
// I will convert to int and check if it is divisible
// by 10 or 5
int i = (int)Math.round(money * 100); // Convert to pennies
if (0 == i % 5) {
// It's ok, return
return money;
}
}
}
Side note: using floating point for currency is bad practice. Floating point can introduce rounding errors. It's better to use integers and store the values using the lowest denomination. In this case pennies.

Addition in Java program equals different value

I'm having a problem with this Java code. It's a questionnaire that should calculate your grade. It all goes and runs well until the very last part where it says "current score" that whole equation should equal 33.16 but instead it equals 24.
I changed some values, did some research but I haven't found what I'm looking for.
import java.util.Scanner;
public class GradeCalculator {
public static void main(String[] args) {
System.out.println("Grading Scale:");
System.out.println("A\t 90 - 100");
System.out.println("B\t 80 - 89");
System.out.println("C\t 70 - 79");
System.out.println("D\t 60 - 69");
System.out.println("F\t below 60");
System.out.println("What letter grade do you want to achieve for the course?");
String desiredGrade;
Scanner keyboard = new Scanner(System.in);
desiredGrade = keyboard.next();
if (desiredGrade.equalsIgnoreCase("A") || desiredGrade.equalsIgnoreCase("B")
|| desiredGrade.equalsIgnoreCase("C") || desiredGrade.equalsIgnoreCase("D")
|| desiredGrade.equalsIgnoreCase("F")) {// is this necessary? vv
System.out.println("Enter Percentage Weights");
}
else {
System.out.println("Input error.");
System.exit(0);
}
int exam1, exam2, finalExam, labs, projects, attendance, quizzes;
System.out.println("Exam 1:\t");
exam1 = keyboard.nextInt();
System.out.println("Exam 2:\t");
exam2 = keyboard.nextInt();
System.out.println("Final Exam:\t");
finalExam = keyboard.nextInt();
System.out.println("Labs:\t");
labs = keyboard.nextInt();
System.out.println("Projects:\t");
projects = keyboard.nextInt();
System.out.println("Attendance:\t");
attendance = keyboard.nextInt();
System.out.println("Quizzes:\t");
quizzes = keyboard.nextInt();
// so the semicolon isn't needed after the if statement?
if (exam1 + exam2 + finalExam + labs + projects + attendance + quizzes != 100) {
System.out.println("Weights don't add up to 100, program exiting");
System.exit(0);
}
System.out.println("Enter your scores out of a 100:");
System.out.println("Do you know your Exam 1 score?");
String answer;
int exam1score = 0, exam2score = 0, finalExamScore = 0, labAverage = 0, projectAverage = 0, quizAverage = 0, attendanceAverage = 0;
double currentScore = 0;
answer = keyboard.next();
// ask about this
if (answer.equalsIgnoreCase("yes") || answer.equalsIgnoreCase("y")) {
// why can't i put int here?
System.out.println("Score received on exam 1:");
exam1score = keyboard.nextInt();
System.out.println("Do you know your Exam 2 score?");
answer = keyboard.next();
if (answer.equalsIgnoreCase("yes") || answer.equalsIgnoreCase("y")) {
System.out.println("Score received on exam 2:");
exam2score = keyboard.nextInt();
System.out.println("Do you know your Final Exam score?");
answer = keyboard.next();
}
if (answer.equalsIgnoreCase("yes") || answer.equalsIgnoreCase("y")) {
System.out.println("Score received on final exam");
finalExamScore = keyboard.nextInt();
}
}
System.out.println("Do you know your lab average?");
answer = keyboard.next();
if (answer.equalsIgnoreCase("yes") || answer.equalsIgnoreCase("y")) {
System.out.println("Average Lab Grade:");
labAverage = keyboard.nextInt();
}
System.out.println("Do you know your project average?");
answer = keyboard.next();
if (answer.equalsIgnoreCase("yes") || answer.equalsIgnoreCase("y")) {
System.out.println("Average Project Grade:");
projectAverage = keyboard.nextInt();
}
System.out.println("Do you know your quiz average?");
answer = keyboard.next();
if (answer.equalsIgnoreCase("yes") || answer.equalsIgnoreCase("y")) {
System.out.println("Average Quiz Grade:");
quizAverage = keyboard.nextInt();
}
System.out.println("Do you know your attendance average?");
answer = keyboard.next();
if (answer.equalsIgnoreCase("yes") || answer.equalsIgnoreCase("y")) {
System.out.println("Average Attendance Grade:");
attendanceAverage = keyboard.nextInt();
}
currentScore = ((double)exam1score*exam1 + exam2score*exam2 +finalExam*finalExamScore + labs*labAverage + projects*projectAverage + attendance*attendanceAverage + quizzes*quizAverage)/((double)exam1+exam2+finalExam+labs+projects+attendance+quizzes);
System.out.println("Current Grade Score:\t " + currentScore);
String grade;
if (currentScore >= 90)
grade = "A";
else if (currentScore >= 80)
grade = "B";
else if (currentScore >= 70)
grade = "C";
else if (currentScore >= 60)
grade = "D";
else
grade = "F";
}
}
The following only converts the exam1score*exam1 value to double, not the entire expression.
(double) exam1score*exam1 + exam2score*exam2 + finalExam*finalExamScore + ....
So, you should do something like this.
int nominator = exam1score*exam1 + exam2score*exam2 + finalExam*finalExamScore
+ labs*labAverage + projects*projectAverage
+ attendance*attendanceAverage + quizzes*quizAverage;
int denominator = exam1 + exam2 + finalExam + labs + projects + attendance + quizzes;
currentScore = (double) nominator / denominator;
OR
int nominator = exam1score*exam1 + exam2score*exam2 + finalExam*finalExamScore
+ labs*labAverage + projects*projectAverage
+ attendance*attendanceAverage + quizzes*quizAverage);
int denominator = exam1 + exam2 + finalExam + labs + projects + attendance + quizzes;
currentScore = (nominator * 1.0) / denominator;
(double)exam1score*exam1 + exam2score*exam2 +finalExam*finalExamScore + labs*labAverage + projects*projectAverage + attendance*attendanceAverage + quizzes*quizAverage
only converts the first one to double and leaves the rest as int.

Getting "while expected" error in "do...while" loop

I keep getting this error and I am not stuck trying to fix it.
package bonuscalc;
import java.text.DecimalFormat;
import java.util.Scanner;
public class BonusCalc {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
DecimalFormat formatter = new DecimalFormat("#0.00");
int Salary;
double NewSal, Comm;
double p1 = 0.1;
double p2 = 0.15;
double p3 = 0.2;
double p4 = 0.3;
System.out.println("Welcome to Bonus Calculator");
do{
System.out.print("Enter your Salary: ");
Salary = input.nextInt();
}While (Salary < 0)
if((Salary > 0) && (Salary <= 8000)){
Comm = (Salary * p1);
NewSal = Salary + Comm;
System.out.print("Your Commition is RM" + formatter.format(Comm));
System.out.println(" and your New Salary is RM" + formatter.format(NewSal));
}
else if((Salary > 8000) && (Salary <= 15000)){
Comm = (Salary * p2);
NewSal = Salary + Comm;
System.out.print("Your Commition is RM" + formatter.format(Comm));
System.out.println(" and your New Salary is RM" + formatter.format(NewSal));
}
else if((Salary > 15000) && (Salary <= 25000)){
Comm = (Salary * p3);
NewSal = Salary + Comm;
System.out.print("Your Commition is RM" + formatter.format(Comm));
System.out.println(" and your New Salary is RM" + formatter.format(NewSal));
}
else if(Salary > 25000){
Comm = (Salary * p4);
NewSal = Salary + Comm;
System.out.print("Your Commition is RM" + formatter.format(Comm));
System.out.println(" and your New Salary is RM" + formatter.format(NewSal));
}
else{
System.out.println("Input invalid. Renter Salary");
}
}
}
You have written While instead of while.
do {
...
} While (Salary < 0);
correct would be:
do {
...
} while (Salary < 0);
Hope this solves your problem.
Your do-while loop has an invalid syntax. Firstly, while is lowercase, thus While is incorrect. Moreover, you are missing a semicolon.
do {
System.out.print("Enter your Salary: ");
Salary = input.nextInt();
} while (Salary < 0);
On a side note, in Java variables usually start with lowercase letters. It is not a strict rule, but a convention that it is prudent to conform to.

The local variable may not have been initialized issue?

So I am trying to create a list without creating an array list, however, whenever I try to run the program I get the error "The local variable "letterGrade" may not have been initialized" I have tried changing the whole code but I still have the same problem >.< any help will be greatly appreciated. Thank you in advance.
import java.util.Scanner;
public class KifahProg4
{
public static void main(String[] args)
{
Scanner stdIn = new Scanner(System.in);
String lastName,firstName,fullName,list;
int score,countA,countB,countC,countD,countF; //Student scores and number of Grades
int total = 0; //Student total score
double average; //Student Average score
char letterGrade; //Student grade
char response; //User continue y/n
do
{
System.out.print("Enter the student last name: ");
lastName = stdIn.next();
System.out.print("Enter the student first name: ");
firstName = stdIn.next();
fullName = lastName + " " + firstName;
for (int i=0; i<=5; i++)
{
System.out.print("Enter the score: ");
score = stdIn.nextInt();
total += score;
average = (double) total/5;
if(average >= 90 && average <=100)
{
letterGrade = 'A';
}
else if (average >=80)
{
letterGrade = 'B';
}
else if (average >=70)
{
letterGrade = 'C';
}
else if (average >= 60)
{
letterGrade = 'D';
}
else if (average <= 59)
{
letterGrade = 'F';
}
System.out.println("Grade is: " );
list = fullName + "\t" + total + average + "\t" + letterGrade + "\n";
}
System.out.println(
"Would you like to add another student? (y/n): ");
response = stdIn.next().charAt(0);
} while (response == 'y' || response == 'Y');
} // end main
} // end class KifahProg4
Set letterGrade to some default value before you use it to get rid of the compiler warning you're getting.
e.g.
char letterGrade = 'Z';
If it is still set to 'Z' when you get to list = fullName + "\t" + total + average + "\t" + letterGrade + "\n"; you know you have an error condition...

Java JoptionPane trying to get it to work for sepreate method with double x4

i am trying to get my program to just show the grade and letter grade i know its a mess but i just need it to print but the Netbean says that JOptionPane requires double, double, double, double
package garrett_sprunger_a5;
import java.text.DecimalFormat;
import java.util.Scanner;
import javax.swing.JOptionPane;
/**
*
* #author Garrett
*/
public class Garrett_sprunger_A5 {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
String inputString; // For reader's input
double TestScore1, //Define TestScore 1
TestScore2, //Define TestScore 2
TestScore3, //Define TestScore 3
AverageScore; //Define AverageScore
Scanner keyboard = new Scanner(System.in); //To hold the users grade
// (somehow i am able to use
// keyboard but can't get the
// varible to match correctly)
DecimalFormat formatter =
new DecimalFormat("#,##0.0"); //format the scores
Scanner Keyboard = new Scanner(System.in);
inputString=
JOptionPane.showInputDialog("\t\nPlease enter Test Score 1");
TestScore1 = Double.parseDouble(inputString);
// input TestScore2
inputString=
JOptionPane.showInputDialog("\t\nPlease enter Test Score 2");
// Convert the input to a double
TestScore2 = Double.parseDouble(inputString);
//input TestScore3
inputString=
JOptionPane.showInputDialog("\t\nPlease enter Test Score 3");
// Convert the input to a double
TestScore3 = Double.parseDouble(inputString);
//Calculate the average score for the tests
AverageScore = Calcaverage(TestScore1, TestScore2, TestScore3);
//AverageScore = (AverageScore +0.5);// applying midpoint roudning
// rule not needed with formated
// rounding
//Display Average test Score
{
if(TestScore1 <0 && TestScore1 >100)
JOptionPane.showMessageDialog(null, "Please enter a Correct" +
" data range between 0 and 100");
}
JOptionPane.showMessageDialog(null, "\t\nYour Test Score 1 is : "
+ formatter.format(TestScore1)
+"\t Grade: "
+ getLetterGrade(TestScore1)
+ "\t\nYour Test Score 2 is : "
+ formatter.format(TestScore2)
+ "\t Grade: "
+ getLetterGrade(TestScore2)
+ "\t\nYour Test Score 3 is : "
+ formatter.format(TestScore3)
+ "\t Grade: "
+ getLetterGrade(TestScore3)
+ "\t\nYour Average Score is : "
+ formatter.format(AverageScore)
+ "\t Grade: "
+ getLetterGrade(AverageScore));
}//End main method
public static double Calcaverage(double TestScore1,
double TestScore2, double TestScore3 ) {
double AverageScore = ((TestScore1 + TestScore2 + TestScore3)/3);
return AverageScore;
}
// Determine the letter grade
public static char getLetterGrade(double TestScore1,
double TestScore2,double TestScore3, double AverageScore) {
if (AverageScore >=90) {
return 'A';
} else if (AverageScore >= 70 && AverageScore < 90) {
if (TestScore3 > 90)
return 'A';
} else
return 'B';
if(AverageScore >=50 && AverageScore <70) {
if(((TestScore2 + TestScore3)/2.0) > 70)
return 'C';
} else
return 'D';
if (AverageScore < 50)
return 'f';
else
return '0';
}
public static void displaygrade( double AverageScore,
double TestScore1, double TestScore2,
double TestScore3, char getLetterGrade) {
DecimalFormat formatter = new DecimalFormat("#,##0.0");
JOptionPane.showMessageDialog(null, "\t\nYour Test Score 1 is : " +
formatter.format(TestScore1) +
"\t Grade: " + getLetterGrade(
TestScore1) +
"\t\nYour Test Score 2 is : " +
formatter.format(TestScore2) +
"\t Grade: " + getLetterGrade(
TestScore2) +
"\t\nYour Test Score 3 is : " +
formatter.format(TestScore3) +
"\t Grade: " + getLetterGrade(
TestScore3) +
"\t\nYour Average Score is : " + formatter.format(AverageScore)+
"\t Grade: " + getLetterGrade(
AverageScore));
}
}
I suggest you change the getLetterGrade() method to something which resembles this:
public static char getLetterGrade(double testScore) {
if (testScore >= 90) {
return 'A';
}
else if (testScore >= 80) {
return 'B';
}
//continue using if statements to determine the letter grade
}
Note that the method above only has one parameter, double testScore, which should be more helpful than inputing four doubles at once.
Would also like to point out that this if statement in your code will never run. Should be easy to figure out why:
if(TestScore1 <0 && TestScore1 >100)
JOptionPane.showMessageDialog(null, "Please enter a Correct data range between 0 and 100");

Categories

Resources