Simple java: error with if statements - java

So I have been trying to figure this out for the past 5 hours and the reason being...from a beginner point of view this code looks fine with no errors but the output is still wrong...basically for every 10 kids tickets the user gets one free,so the output is fine if the free tickets is less than the adults but it subtracts the extra adults when its the other way around.
package theatre;
import java.util.*;
public class Theatre {
public static void main(String[] args) {
Scanner kybd = new Scanner(System.in);
System.out.println("Enter the number of tickets you would like to buy for each type: ");
System.out.println("Adult: £10.50");
System.out.println("Child: £7.30");
System.out.println("Concessions £8.40");
System.out.println("Adult: ");
int Adult = kybd.nextInt();
System.out.println("Child: ");
int Child = kybd.nextInt();
System.out.println("Concessions: ");
int concessions = kybd.nextInt();
int freeAdult = Child / 10;
if (freeAdult < 9) {
System.out.println("You get " + freeAdult + " adult tickets");
} else {
System.out.println("You don't get any free tickets");
}
System.out.println(freeAdult); //reference out
double adultBill = (Adult * 10.50) - (freeAdult * 10.50);
double childBill = Child * 7.30;
double concessionsBill = concessions * 8.40;
double totalBill = adultBill + childBill + concessionsBill;
double totalBill2 = childBill + concessionsBill;
System.out.println(totalBill2); //reference out
if (freeAdult >= Adult) {
System.out.printf("Total bill is: £%.2f\n", totalBill);
} else if (freeAdult < Adult) {
System.out.printf("Total bill is: £%.2f\n", totalBill2);
} else {
System.out.println("Please enter a corrrect value");
}
}
}
Thanks

I think you have your logic a little confused:
int freeAdult = Child / 10;
if (freeAdult < 9) {
System.out.println("You get " + freeAdult + " adult tickets");
} else {
System.out.println("You don't get any free tickets");
}
appears to be calculating how many free adult tickets the person gets based on the number of child tickets (Child / 10) ...but is then saying they get no tickets if they've qualified for more than 10? I think you might be using the wrong variable here. Then:
double adultBill = (Adult * 10.50) - (freeAdult * 10.50);
double childBill = Child * 7.30;
double concessionsBill = concessions * 8.40;
double totalBill = adultBill + childBill + concessionsBill;
double totalBill2 = childBill + concessionsBill;
System.out.println(totalBill2); //reference out
if (freeAdult >= Adult) {
System.out.printf("Total bill is: £%.2f\n", totalBill);
} else if (freeAdult < Adult) {
System.out.printf("Total bill is: £%.2f\n", totalBill2);
} else {
System.out.println("Please enter a corrrect value");
}
I believe is meant to calculate 2 bills, one including adults and one not and then if the number of free adult tickets is greater than the number of adults, discard the first bill and use the second (which never included the adults calculation), in which case you have your if statement the wrong way around, it should be:
if (freeAdult < Adult) {
System.out.printf("Total bill is: £%.2f\n", totalBill);
} else if (freeAdult >= Adult) {
System.out.printf("Total bill is: £%.2f\n", totalBill2);
...however you should only have to calculate one bill by simply changing the adult calculation to:
double adultBill = freeAdult < Adult ? (Adult * 10.50) - (freeAdult * 10.50) : 0;
Then calculate bill as normal:
double totalBill = adultBill + childBill + concessionsBill;
System.out.printf("Total bill is: £%.2f\n", totalBill);

public class Theatre {
public static void main(String[] args) {
Scanner kybd = new Scanner(System.in);
System.out.println("Enter the number of tickets you would like to buy for each type: ");
System.out.println("Adult: £10.50");
System.out.println("Child: £7.30");
System.out.println("Concessions £8.40");
System.out.println("Adult: ");
int adult = kybd.nextInt();
System.out.println("Child: ");
int child = kybd.nextInt();
System.out.println("Concessions: ");
int concessions = kybd.nextInt();
int freeAdult = child / 10;
System.out.println("You get " + freeAdult + " adult tickets free");
if(adult >0){
adult = adult - freeAdult;
}
double adultBill = (adult * 10.50);
double childBill = child * 7.30;
double concessionsBill = concessions * 8.40;
double totalBill = adultBill + childBill + concessionsBill;
System.out.printf("Total bill is: £%.2f\n", totalBill);
}
}

Related

Program is not quitting when choice 2 is entered instead it is asking to enter a positive number. What is the issue here?

The program is not quitting when choice 2 is entered instead it's asking to enter a positive value. It should only ask that if the choice was 1 and then the number of rooms entered was less than one. It should immediately quit the program but it's not. What can I do to fix this? Is it because of braces missing or extra ones.
import java.util.Scanner;
import java.text.DecimalFormat;
public class Paint {
public static void main(String[] args) {
DecimalFormat formatter = new DecimalFormat("###0.00");
Scanner keyboard = new Scanner(System.in);
double numbGallons;
double costPerGallon;
double totalSquareFeet = 0;
double numbHours;
double costPerHour;
double paintCost1;
double squareFeet;
int choice;
int numRooms = 0;
double laborCost1;
double totalEstimate;
do {
displayMenu();
choice = keyboard.nextInt();
if (choice == 1) {
System.out.println("How many rooms do you want to paint?");
numRooms = keyboard.nextInt();
}
while (numRooms < 1) {
System.out.println("Please enter a positive value");
numRooms = keyboard.nextInt();
}
for (int counter = 1; counter <= numRooms; counter++) {
System.out.println("How many square feet of room " + counter +
" do you want to paint?");
squareFeet = keyboard.nextDouble();
totalSquareFeet = totalSquareFeet + squareFeet;
}
System.out.println("The total square feet is " + totalSquareFeet);
numbGallons = numGallons(totalSquareFeet);
numbHours = numHours(totalSquareFeet);
System.out.println("How much is the price per hour?");
costPerHour = keyboard.nextDouble();
System.out.println("How much is the price per gallon?");
costPerGallon = keyboard.nextDouble();
laborCost1 = laborCost(costPerHour, numbHours);
paintCost1 = paintCost(numbGallons, costPerGallon);
System.out.println("The number of Gallons is " + numbGallons);
System.out.println("The number of Hours is " + numbHours);
System.out.println("The labor cost is " + laborCost1);
System.out.println("The paint cost is " + paintCost1);
totalEstimate = laborCost1 + paintCost1;
System.out.println("The total estimate is " + totalEstimate);
} while (choice != 2);
}
public static void displayMenu() {
System.out.println("1)Calculate Estimate");
System.out.println("2)Quit the program");
System.out.println("Please make a selection");
}
public static double numGallons(double sqr) {
return sqr / 115;
}
public static double numHours(double sqr) {
return (sqr / 115) * 8;
}
public static double laborCost(double cph, double nh) {
return cph * nh;
}
public static double paintCost(double ng, double cpg) {
return ng * cpg;
}
}
You should show the menu and get the choice before entering the loop, and at the end of the loop.
public static void main(String[] args) {
DecimalFormat formatter = new DecimalFormat("###0.00");
Scanner keyboard = new Scanner(System.in);
double numbGallons;
double costPerGallon;
double totalSquareFeet = 0;
double numbHours;
double costPerHour;
double paintCost1;
double squareFeet;
int choice;
int numRooms = 0;
double laborCost1;
double totalEstimate;
displayMenu();
choice = keyboard.nextInt();
while (choice != 2) {
//if (choice ==1)
//{
System.out.println("How many rooms do you want to paint?");
numRooms = keyboard.nextInt();
//}
while (numRooms < 1) {
System.out.println("Please enter a positive value");
numRooms = keyboard.nextInt();
}
for (int counter = 1; counter <= numRooms; counter++) {
System.out.println("How many square feet of room " + counter +
" do you want to paint?");
squareFeet = keyboard.nextDouble();
totalSquareFeet = totalSquareFeet + squareFeet;
}
System.out.println("The total square feet is " + totalSquareFeet);
numbGallons = numGallons(totalSquareFeet);
numbHours = numHours(totalSquareFeet);
System.out.println("How much is the price per hour?");
costPerHour = keyboard.nextDouble();
System.out.println("How much is the price per gallon?");
costPerGallon = keyboard.nextDouble();
laborCost1 = laborCost(costPerHour, numbHours);
paintCost1 = paintCost(numbGallons, costPerGallon);
System.out.println("The number of Gallons is " + numbGallons);
System.out.println("The number of Hours is " + numbHours);
System.out.println("The labor cost is " + laborCost1);
System.out.println("The paint cost is " + paintCost1);
totalEstimate = laborCost1 + paintCost1;
System.out.println("The total estimate is " + totalEstimate);
displayMenu();
choice = keyboard.nextInt();
}
}

Finding out how many times a user is processed?

I'm having some trouble with a part of an assignment. I have to see how many times an employee is processed in my program, after the loop runs once it asks the user if they would like to process another. If they enter y for yes and then they enter n for end after the second employee calculation. I want it to say "Number of employees processed: 2". How could I do this?
package paytime;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scn = new Scanner(System.in);
String firstName, lastName, choice;
double hoursWorked, hourlyWage;
boolean processAnotherEmployee = true;
Employee one = new Employee();
while(true)
{
if (processAnotherEmployee)
{
System.out.print("Enter Y to process employee or any other key to end: ");
choice = scn.next();
if (choice.equalsIgnoreCase("Y"))
{
System.out.print("Enter employee number: ");
int number = scn.nextInt();
while (!one.findEmpNumber(number))
{
System.out.print("Invlaid, enter a proper employee number: ");
number = scn.nextInt();
}
System.out.print("Enter first name: ");
firstName = scn.next();
System.out.print("Enter last name: ");
lastName = scn.next();
System.out.print("Enter hours worked: ");
hoursWorked = scn.nextDouble();
while (hoursWorked < 0)
{
System.out.print("Negative hours not allowed. Enter hours worked: ");
hoursWorked = scn.nextDouble();
}
System.out.print("Enter hourly wage: $");
hourlyWage = scn.nextDouble();
while (hourlyWage < 0 || hourlyWage > 100)
{
System.out.print("Negative wage is not allowed or wage entered is to high. Enter hourley wage: $");
hourlyWage = scn.nextDouble();
}
double overtimeHours = hoursWorked - 40;
double overtimeWage = hourlyWage * 1.5;
System.out.println(" ");
if (hoursWorked <= 40.0)
{
System.out.println("Worker " + number + " Paycheck Information: ");
System.out.println("Name is: " + firstName + " " + lastName);
System.out.println("Weekly Pay is: " + one.callWeeklyPay(hoursWorked, hourlyWage));
System.out.println("Income Taxes is: " + one.callIncomeTax());
System.out.println("Net Pay is: " + one.callNetPay());
}
else if (hoursWorked > 40.0)
{
System.out.println("Worker " + number + " Paycheck Information: ");
System.out.println("Name is: " + firstName + " " + lastName);
System.out.println("Weekly Pay is: " + one.callWeeklyPay(hoursWorked, hourlyWage));
System.out.println("Income Taxes is: " + one.callIncomeTax());
System.out.println("Net Pay is: " + one.callNetPay());
System.out.println(" ");
System.out.println("Worker " + number + " Overtime Calculation: ");
System.out.println("Overtime Pay is: " + one.callOvertimePay(overtimeHours, overtimeWage, hourlyWage, hoursWorked));
System.out.println("Overtime Income Tax is: " + one.callOvertimeTax());
System.out.println("Overtime Net Pay is: " + one.callOvertimeNetPay());
System.out.println("Total Net Pay is: " + one.callTotalNetPay());
System.out.println(" ");
}
}
else if (!choice.equalsIgnoreCase("Y"))
{
processAnotherEmployee = false;
System.out.println("Total number of Employees processed: ");
System.out.println(" ");
System.out.println("End of program");
break;
}
}
}
}
}
and
package paytime;
public class Employee {
private int empNumbers [] = {101, 103, 106, 109, 110, 113, 116, 118, 120};
public double weeklyPay, hoursWorked, hourlyWage, incomeTax, netPay,
overtimePay, overtimeHours, overtimeWage, overtimeIncomeTax,
overtimeNetPay, totalNetPay;
public boolean findEmpNumber(int number)
{
boolean found = false;
for (int sub = 0; sub < empNumbers.length; sub++)
{
if (number == empNumbers[sub])
{
found = true;
break;
}
}
return found;
}
private void calculateWeeklyPay(double hoursWorked, double hourlyWage) {
if (hoursWorked > 40)
{
hoursWorked = 40;
weeklyPay = hoursWorked * hourlyWage;
}
else
{
weeklyPay = hoursWorked * hourlyWage;
}
}
public double callWeeklyPay(double hoursWorked, double hourlyWage) {
calculateWeeklyPay(hoursWorked, hourlyWage);
return weeklyPay;
}
private void calculateIncomeTax() {
if (weeklyPay > 0.0 && weeklyPay <= 300.0)
{
incomeTax = weeklyPay * 0.10;
}
else if (weeklyPay > 300.1 && weeklyPay <= 400.0)
{
incomeTax = weeklyPay * 0.12;
}
else if (weeklyPay > 400.1 && weeklyPay <= 500.0)
{
incomeTax = weeklyPay * 0.15;
}
else if (weeklyPay > 500.1)
{
incomeTax = weeklyPay * 0.20;
}
}
public double callIncomeTax() {
calculateIncomeTax();
return incomeTax;
}
private void calculateNetPay() {
netPay = weeklyPay - incomeTax;
}
public double callNetPay() {
calculateNetPay();
return netPay;
}
private void calculateOvertimePay(double overtimeHours, double overtimeWage, double hourlyWage, double hoursWorked) {
overtimePay = overtimeHours * overtimeWage;
}
public double callOvertimePay(double overtimeHours, double overtimeWage, double hourlyWage, double hoursWorked) {
calculateOvertimePay(overtimeHours, overtimeWage, hourlyWage, hoursWorked);
return overtimePay;
}
private void calculateOvertimeTax() {
overtimeIncomeTax = overtimePay * 0.25;
}
public double callOvertimeTax() {
calculateOvertimeTax();
return overtimeIncomeTax;
}
private void calculateOvertimeNetPay() {
overtimeNetPay = overtimePay - overtimeIncomeTax;
}
public double callOvertimeNetPay() {
calculateOvertimeNetPay();
return overtimeNetPay;
}
private void calculateTotalNetPay() {
totalNetPay = netPay + overtimeNetPay;
}
public double callTotalNetPay() {
calculateTotalNetPay();
return totalNetPay;
}
}
You can achieve this by simply having "int employeesProcessed = 0;" outside of you while loop then add "employeesProcessed++;" directly after "if (choice.equalsIgnoreCase("Y"))" so that each time your program is asked to process an employ you add 1 to your int that is keeping track of how many employees you have processed. Then you can add this variable onto the end of your printed string so it says "Total number of Employees processed: " + employeesProcessed.

Aggregating results of different calculations

This is my first post here, so forgive me for any formatting errors.
So as you can see my program requests the gender, # of accidents and year of car to display a fictitious insurance quote.
Based on all that information I need to add the subtotal of the insurance cost to the end.
I have my code working up until the Total Cost comment (posted it all for reference). I am stuck there because the genders have different base amounts. I'm trying to figure out a way to only do one if statement if it matches the gender that was input by the user.
Any ideas?
import java.util.*;
public class Insurance {
public static void main(String [] args) {
Scanner scanner = new Scanner(System.in);
int currentYear = 2017; //used for calculating the age of the users car
int maleGender = 1000;
int femaleGender = 500;
//Letting user know they are inputting data for car insurance purposes
System.out.println("Car insurance questionnaire. Please input correct information when prompted.");
// gender information from user
System.out.println("What is your gender? m/f");
String gender = scanner.next();
// accident quantity information from user
System.out.println("How many accidents have you had?");
int acc = scanner.nextInt();
// car year information from user
System.out.println("What year was your car manufactured?");
int carAge = scanner.nextInt();
//if statements which refer to the users data input
if (gender.equals("m")) {
System.out.println("You are a male.\nThe base cost is $1000.");
} else {
System.out.println("You are a female.\nThe base cost is $500.");
}
if (acc == 0) {
System.out.println("You have no accidents. Insurance increase is $0.");
} else if (acc >= 1) {
System.out.println("You have " + acc + " accidents. Insurance increase is $" + acc * 100 + ".");
}
if (carAge >= 2007) {
System.out.println("Your car is " + (currentYear - carAge) + " years old.\nYour car is still in warranty, no savings added.");
} else
System.out.println("Your car is out of warranty, final cost is halved.");
//Total cost
/*
if (carAge <= 2007) {
System.out.println("Your total price is $" + ((acc * 100 + femaleGender) / 2) + ".");
} else
System.out.println("Your total price is $" + (acc * 100 + femaleGender) + ".");
*/
}
}
I am not totally sure how you want to calculate your result but if do NOT want to use femaleGender all the time but in dependency of the gender different values then maybe something like this could help:
int baseAmount = gender.equals("m") ? maleGender : femaleGender;
if (carAge <= 2007) {
System.out.println("Your total price is $" + ((acc * 100 + baseAmount ) / 2) + ".");
} else
System.out.println("Your total price is $" + (acc * 100 + baseAmount ) + ".");
}
int genderCost;
...
if (gender.equals("m")) {
System.out.println("You are a male.\nThe base cost is $1000.");
genderCost = maleGender;
} else {
System.out.println("You are a female.\nThe base cost is $500.");
genderCost = femaleGender;
}
...
if (carAge <= 2007) {
System.out.println("Your total price is $" + ((acc * 100 + genderCost) / 2) + ".");
} else
System.out.println("Your total price is $" + (acc * 100 + genderCost) + ".");
}
Put the amount for gender in a variable genderCost when the gender input variable is evaluated and use genderCost when you calculate the total.

Formatting decimal point in JOptionPane.showMessageDialog

My code has been an evolving process and the end game is to implement a UI using JOptionPane to my previous iteration. I successfully formatted an output to a 2 decimal place using String.format("Text goes here %.2f", variable) but when I try to carry this method over to my iteration of code using JOptionPane it crashes the program.
Here is my code
import javax.swing.JOptionPane;
public class Ass1d2
{
public static void main(String [] args)
{
final int N = 7;
String taxPayerName;
int taxPayerIncome = 0;
double maxTax = 0.0;
String maxTaxName = "";
JOptionPane.showMessageDialog(null, "Welcome to use Tax Computation System");
for(int i = 0; i < N; i++)
{
taxPayerName = (String)JOptionPane.showInputDialog(null, "Enter tax payers name");
taxPayerIncome = Integer.parseInt(JOptionPane.showInputDialog(null, "Enter income for the tax payer"));
double tax = computeTax(taxPayerIncome);
if (taxPayerIncome > maxTax){
maxTax = tax;
maxTaxName = taxPayerName;
}
JOptionPane.showMessageDialog(null, "The tax that " + taxPayerName + " owes is $" + tax));
}
JOptionPane.showMessageDialog(null, "The maximum tax is $" + maxTax) + " paid by " + maxTaxName);
}
private static double computeTax(int taxPayerIncome)
{
double tax = 0.0;
if (taxPayerIncome < 18200)
tax = 0;
else if (taxPayerIncome < 37000)
tax = (taxPayerIncome - 18200) * 0.19;
else if (taxPayerIncome < 87000)
tax = 3572 + (taxPayerIncome - 37000) * 0.325;
else if (taxPayerIncome < 180000)
tax = 19822 + (taxPayerIncome - 87000) * 0.37;
else
tax = 54232 + (taxPayerIncome - 180000) * 0.47;
return tax;
}
}
How do I format the two showMessageDialog to produce a two decimal floating point result? I've been scouring guides for the past hour and it's just not clicking. Very frustrating that this is the final roadblock. Thanks.
Well I must have done a typo in my other attempts as I have it working now. Awkward. Attached updated code with working floating point result for future reference.
import javax.swing.JOptionPane;
public class Ass1d2
{
public static void main(String [] args)
{
final int N = 3;
String taxPayerName;
int taxPayerIncome = 0;
double maxTax = 0.0;
String maxTaxName = "";
JOptionPane.showMessageDialog(null, "Welcome to use Tax Computation System");
for(int i = 0; i < N; i++)
{
taxPayerName = (String)JOptionPane.showInputDialog(null, "Enter tax payers name");
taxPayerIncome = Integer.parseInt(JOptionPane.showInputDialog(null, "Enter income for the tax payer"));
double tax = computeTax(taxPayerIncome);
if (taxPayerIncome > maxTax){
maxTax = tax;
maxTaxName = taxPayerName;
}
JOptionPane.showMessageDialog(null, "The tax that " + taxPayerName + " owes is $" + String.format("%.2f", tax));
}
JOptionPane.showMessageDialog(null, "The maximum tax is $" + String.format("%.2f", maxTax) + " paid by " + maxTaxName);
}
private static double computeTax(int taxPayerIncome)
{
double tax = 0.0;
if (taxPayerIncome < 18200)
tax = 0;
else if (taxPayerIncome < 37000)
tax = (taxPayerIncome - 18200) * 0.19;
else if (taxPayerIncome < 87000)
tax = 3572 + (taxPayerIncome - 37000) * 0.325;
else if (taxPayerIncome < 180000)
tax = 19822 + (taxPayerIncome - 87000) * 0.37;
else
tax = 54232 + (taxPayerIncome - 180000) * 0.47;
return tax;
}
}

Error code compiling: illegal start of expression [closed]

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

Categories