How do I state the }while(???) portion of the loop? - java

I need this code to loop for however many iterations someone decides to use, I do not understand what condition I would need to put into the {while**(??here??)**;
Also I understand that the loop should go around my input statements and tax computation, have I placed the do and the while in the right position?
EDIT* I've removed 2 of the cases from the code which are pretty much the same so I could post within the rules here.
import java.util.Scanner;
public class Assignment333 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
do {
System.out.println("Enter your first name:");
String name = input.next();
System.out.println("Enter your age in years:");
byte age = input.nextByte();
System.out.println("Enter your gender (F/M):");
char gender = input.next().charAt(0);
System.out.println("Enter your marital status (S/M/D/W):");
char marital_status = input.next().charAt(0);
System.out.println("Enter your taxable income for 2016:");
long income = input.nextLong();
String name_prefix;
double tax_amount;
if (gender == 'M') {
name_prefix = (age < 18) ? "Master." : "Mr.";
} else {
name_prefix = (marital_status == 'M') ? "Mrs." : "Ms.";
}
switch (marital_status) {
case 'M':
if (income < 8500) {
tax_amount = 0;
System.out.println(name_prefix + " " + name + ", based on the income provided, you owe no tax for the fiscal year 2016");
} else {
if (income < 24000) {
tax_amount = income * 0.01;
} else {
tax_amount = income * 0.025;
}
System.out.println(name_prefix + " " + name + ", based on the income provided, you owe a tax of $" + tax_amount + " for the fiscal year 2016");
}
break;
case 'W':
if (income < 8500) {
tax_amount = 0;
System.out.println(name_prefix + " " + name + ", based on the income provided, you owe no tax for the fiscal year 2016");
} else {
if (income < 24000) {
tax_amount = income * .015;
} else {
tax_amount = income * 0.034;
}
System.out.println(name_prefix + " " + name + ", based on the income provided, you owe a tax of $" + tax_amount + " for the fiscal year 2016");
}
while ()
}
break;
default: System.out.println("Sorry! Our system is unable to calculate your tax at this time.");
}
System.out.println("Thank you!");
//closing all objects
input.close();
}
}

You can finish it like this:
...
System.out.println("Would you like to try again? (y/n)");
} while (Objects.equals("y", input.next()))
...

Related

My program is printing the error message twice when a char is entered, how to do I print only once when the char is entered?

I am building a program that checks your salary and returns the amount of tax that you will pay for that financial year.
When the user inserts a character instead of an int, the code below prints the error message twice. How do I change that so it only prints the message once.
Any help would be appreciated. I know the error is occurring in the if statement but I do not know how to change it to detect that the input from user is a char or not.
/* this code works bar one thing with
1: When a Char is entered, it prints an error message twice - doesn't do this when a negative number is entered.
*/
import java.util.Scanner;
public class MyProgram {
public static void main(String[] args) {
// call scanner for user input
Scanner in = new Scanner(System.in);
// double for salary
int salary = 0;
double incomeTax = 0;
double weeklyIncome;
do {
System.out.println("Please enter your salary?");
try {
salary = in.nextInt();
// test if user enters something other than an integer
} catch (java.util.InputMismatchException e) {
System.out.println("Invalid input, only enter a number");
salary = Integer.MIN_VALUE; in.next(); // consume the non-int so we don't get caught in an endless loop\
}
if (salary <= 0) {
System.out.println("Invalid input, please enter a number above 0");
}
}
while (salary <= 0); // loop as long as the salary is less than zero
if (salary <= 18000 & salary > 0) {
incomeTax = 0;
System.out.println("your salary is $" + salary + ", you will pay no income tax this financial year.");
} else if (salary >= 18201 & salary <= 45000) {
incomeTax = (0.19 * (salary - 18200));
weeklyIncome = (salary/52);
System.out.println("your weekly income is $" + weeklyIncome);
System.out.println("you will pay $" + incomeTax + " in tax this financial year.");
} else if (salary >= 45001 & salary <= 120000) {
incomeTax = 5062 + (0.325 * (salary - 45000));
weeklyIncome = (salary/52);
System.out.println("your weekly income is $" + weeklyIncome);
System.out.println("you will pay $" + incomeTax + " in tax this financial year.");
} else if (salary >= 120001 & salary <= 180000) {
incomeTax = 29467 + (0.37 * (salary - 120000));
weeklyIncome = (salary/52);
System.out.println("your weekly income is $" + weeklyIncome);
System.out.println("you will pay $" + incomeTax + " in tax this financial year.");
} else if (salary >= 180001) {
incomeTax = 51667 + (0.45 * (salary - 180000));
weeklyIncome = (salary/52);
System.out.println("your weekly income is $" + weeklyIncome);
System.out.println("you will pay $" + incomeTax + " in tax this financial year.");
}
in .close();
}
}

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.

Do While loop with Yes = start again No = exit Program

I have to add a do-while loop to my project so after the program iterates it says: "You want a run this program again? (Yes or No)"
If user inputs are Yes or YEs or YES or yEs or yES or yeS
It runs a program again.
If it's no, program should automatically exit.
import java.text.DecimalFormat;
import java.util.Scanner;
public class CalculatePay {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
String Name = " ";
int hours;
double payRate;
char F;
char P;
char T;
String input = " ";
char repeat = input.charAt(0);
double grossPay;
int attempt = 0;
System.out.print("What is your name? ");
Name = reader.nextLine();
System.out.print("How many hours did you work? ");
hours = reader.nextInt();
while (hours < 0 || hours > 280)
{
System.out.println("That's not possible, try again!");
hours = reader.nextInt();
attempt++;
if(attempt >= 2) {
System.out.println("You are Fired!");
return ;
}
}
System.out.print("What is your pay rate? ");
payRate = reader.nextDouble();
System.out.print("What type of employee are you? ");
F = reader.next().charAt(0);
grossPay = hours * payRate;
DecimalFormat decFor = new DecimalFormat("0.00");
switch (F)
{
case 'F' :
case 'f' :
System.out.println("Hi " + Name + ", you made $" + decFor.format(grossPay) + " this week"+" as a full-time employee");
if (hours < 0)
{
System.out.println(" That's not possible ");
}
else if (hours > 280)
{
System.out.print(" That's not possible ");
}
else if (grossPay >= 100)
{
System.out.print(" You must be a Java programmer!");
}
else
{
System.out.print(" this week");
}
break;
case 'P' :
case'p' :
System.out.println("Hi " + Name + ", you made $" + decFor.format(grossPay) + " this week"+" as a part- time employee");
if (hours < 0)
{
System.out.println(" That's not possible ");
}
else if (hours > 280)
{
System.out.print(" That's not possible ");
}
else if (grossPay >= 100)
{
System.out.print(" You must be a Java programmer!");
}
else
{
System.out.print(" this week");
}
break;
case 'T' :
case 't' :
System.out.println("Hi " + Name + ", you made $" + decFor.format(grossPay) + " this week"+" as a temporary employee");
if (hours < 0)
{
System.out.println(" That's not possible ");
}
else if (hours > 280)
{
System.out.print(" That's not possible ");
}
else if (grossPay >= 100)
{
System.out.print(" You must be a Java programmer!");
}
else
{
System.out.print(" this week");
}
break;
default:
System.out.println(" unknown employee type");
if (hours < 0)
{
System.out.println(" That's not possible ");
}
else if (hours > 280)
{
System.out.print(" That's not possible ");
}
else if (grossPay >= 100)
{
System.out.print(" You must be a Java programmer!");
}
else
{
System.out.print(" this week");
}
}
System.out.println("Do you want to run this program again? (Yes or No)");
}
}
I suggest yo to wrap your logic in another method, so you can call it later:
import java.text.DecimalFormat;
import java.util.Scanner;
public class CalculatePay {
private static void doStuff() {
Scanner reader = new Scanner(System.in);
String Name = " ";
int hours;
double payRate;
char F;
char P;
char T;
String input = " ";
char repeat = input.charAt(0);
double grossPay;
int attempt = 0;
System.out.print("What is your name? ");
Name = reader.nextLine();
System.out.print("How many hours did you work? ");
hours = reader.nextInt();
while (hours < 0 || hours > 280)
{
System.out.println("That's not possible, try again!");
hours = reader.nextInt();
attempt++;
if(attempt >= 2) {
System.out.println("You are Fired!");
return ; }
}
System.out.print("What is your pay rate? ");
payRate = reader.nextDouble();
System.out.print("What type of employee are you? ");
F = reader.next().charAt(0);
grossPay = hours * payRate;
DecimalFormat decFor = new DecimalFormat("0.00");
switch (F)
{
case 'F' :
case 'f' :
System.out.println("Hi " + Name + ", you made $" + decFor.format(grossPay) + " this week"+" as a full-time employee");
if (hours < 0)
{
System.out.println(" That's not possible ");
}
else if (hours > 280)
{
System.out.print(" That's not possible ");
}
else if (grossPay >= 100)
{
System.out.print(" You must be a Java programmer!");
}
else
{
System.out.print(" this week");
}
break;
case 'P' :
case'p' :
System.out.println("Hi " + Name + ", you made $" + decFor.format(grossPay) + " this week"+" as a part- time employee");
if (hours < 0)
{
System.out.println(" That's not possible ");
}
else if (hours > 280)
{
System.out.print(" That's not possible ");
}
else if (grossPay >= 100)
{
System.out.print(" You must be a Java programmer!");
}
else
{
System.out.print(" this week");
}
break;
case 'T' :
case 't' :
System.out.println("Hi " + Name + ", you made $" + decFor.format(grossPay) + " this week"+" as a temporary employee");
if (hours < 0)
{
System.out.println(" That's not possible ");
}
else if (hours > 280)
{
System.out.print(" That's not possible ");
}
else if (grossPay >= 100)
{
System.out.print(" You must be a Java programmer!");
}
else
{
System.out.print(" this week");
}
break;
default:
System.out.println(" unknown employee type");
if (hours < 0)
{
System.out.println(" That's not possible ");
}
else if (hours > 280)
{
System.out.print(" That's not possible ");
}
else if (grossPay >= 100)
{
System.out.print(" You must be a Java programmer!");
}
else
{
System.out.print(" this week");
}
}
}
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
do {
//Call your bussines logic.
doStuff();
System.out.println("Do you want to run this program again? (Yes or No)");
}
while(reader.nextLine().toLowerCase().equals("yes"));
} }
Note that the function is static. This is because you can not call a non-static method from a static context (main is static).

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.

Need advice with nested if's

I have attempted using a nested if in the following code. I have initialized variables but the compiler is telling me that the variable named 'bill' is not initialized even though it has been. Why is the compiler not recognizing the value assigned to the variable? Please see the notes in the code below.
package killMe;
import java.util.Scanner;
public class Kill_Me {
static Scanner console = new Scanner(System.in);
static double PREMIUM_SERVICE = 55.00;
static double PREMIUM_DAY_OVERTIME_MIN = 0.20;
static double PREMIUM_NIGHT_OVERTIME_MIN = 0.15;
static double REGULAR_SERVICE = 30.00;
static double REGULAR_OVERTIME_MIN = 0.40;
public static void main(String[] args) {
int acctNumber;
double premiumDayMin;
double premiumNightMin;
double bill;
double minutes;
String name;
String premium = "PREMIUM";
String regular = "REGULAR";
System.out.println("What is the Account Number? ");
acctNumber = console.nextInt();
System.out.println("What is the Customer Name? ");
name = console.next();
System.out.println("Is the Service Code Premium or Regular? ");
String strService = console.next();
String strServiceCAP = strService.toUpperCase();
if(strServiceCAP.compareTo(premium) == 0)
{
System.out.println("How many Day Minutes were used? ");
premiumDayMin = console.nextDouble();
System.out.println("How many Night Minutes were used? ");
premiumNightMin = console.nextDouble();
if(premiumDayMin <0 && premiumNightMin <0)
{
System.out.println("Minutes cannot be less than 0 ");
}
else if(premiumDayMin <= 75 && premiumNightMin <= 100)
{
bill = PREMIUM_SERVICE;
}
else bill = PREMIUM_SERVICE + (premiumDayMin - 75) * PREMIUM_DAY_OVERTIME_MIN + (premiumNightMin - 100)
* PREMIUM_NIGHT_OVERTIME_MIN;
minutes = premiumDayMin + premiumNightMin;
System.out.println("Customer Name: " + name);
System.out.println("Account Number: " + acctNumber);
System.out.println("Service Type: " + strServiceCAP);
System.out.println("Minutes Premium Service Used (Day): " + premiumDayMin);
System.out.println("Minutes Premium Service Used (Night): " + premiumNightMin);
System.out.println("Amount Due: " + bill); // I get an error here stating, "The local variable 'bill' may not have been initialized".
}
else if(strServiceCAP.compareTo(regular) == 0)
{
System.out.println("How many minutes were used? ");
minutes = console.nextDouble();
bill = REGULAR_SERVICE + (minutes - 50) * REGULAR_OVERTIME_MIN;
System.out.println("Customer Name: " + name);
System.out.println("Account Number: " + acctNumber);
System.out.println("Service Type: " + strServiceCAP);
System.out.println("Minutes Regular Service Used: " + minutes);
System.out.println("Amount Due: " + bill); // I DO NOT receive an error message here.
}
else
{
System.out.println("Invalid Service Type");
}
} // End of main
} // End of class
No, bill has not been initialized in all cases.
Understand this: the Java compiler will never, ever, evaluate boolean expressions; Simplified version:
double bill;
if (c1) {
bill = v1;
} else if (c2) {
bill = v2;
}
// try and use bill here
Even if, according to your logic, boolean expressions c1 and c2 may cover all possible cases, the compiler cannot ensure that this is the case.
This is the root cause of your error, however deep your if/else, switch, etc statements may be nested.
They were some problems with else statement and variable declarations.
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
double PREMIUM_SERVICE = 25.00;
double PREMIUM_DAY_OVERTIME_MIN = 0.10;
double PREMIUM_NIGHT_OVERTIME_MIN = 0.05;
double REGULAR_SERVICE = 10.00;
double REGULAR_OVERTIME_MIN = 0.20;
int acctNumber;
double premiumDayMin;
double premiumNightMin;
double bill = 0.0;
double minutes;
String name;
String premium = "PREMIUM";
String regular = "REGULAR";
System.out.println("What is the Account Number? ");
acctNumber = console.nextInt();
System.out.println("What is the Customer Name? ");
name = console.next();
System.out.println("Is the Service Code Premium or Regular? ");
String strService = console.next();
String strServiceCAP = strService.toUpperCase();
if(strServiceCAP.compareTo(premium) == 0)
{
System.out.println("How many Day Minutes were used? ");
premiumDayMin = console.nextDouble();
System.out.println("How many Night Minutes were used? ");
premiumNightMin = console.nextDouble();
if(premiumDayMin <0 && premiumNightMin <0)
{
System.out.println("Minutes cannot be less than 0 ");
}
else if(premiumDayMin <= 75 && premiumNightMin <= 100)
{
bill = PREMIUM_SERVICE;
}
else
{
bill = PREMIUM_SERVICE + (premiumDayMin - 75) * PREMIUM_DAY_OVERTIME_MIN + (premiumNightMin - 100)
* PREMIUM_NIGHT_OVERTIME_MIN;
}
minutes = premiumDayMin + premiumNightMin;
System.out.println("Customer Name: " + name);
System.out.println("Account Number: " + acctNumber);
System.out.println("Service Type: " + strServiceCAP);
System.out.println("Minutes Premium Service Used (Day): " + premiumDayMin);
System.out.println("Minutes Premium Service Used (Night): " + premiumNightMin);
System.out.println("Amount Due: " + bill); // I get an error here stating, "The local variable 'bill' may not have been initialized".
}
else if(strServiceCAP.compareTo(regular) == 0)
{
System.out.println("How many minutes were used? ");
minutes = console.nextDouble();
bill = REGULAR_SERVICE + (minutes - 50) * REGULAR_OVERTIME_MIN;
System.out.println("Customer Name: " + name);
System.out.println("Account Number: " + acctNumber);
System.out.println("Service Type: " + strServiceCAP);
System.out.println("Minutes Regular Service Used: " + minutes);
System.out.println("Amount Due: " + bill); // I DO NOT receive an error message here.
}
else
{
System.out.println("Invalid Service Type");
}
} // End of main
}
I'm not sure why it gets this error, but try initialising bill as 0.00 when you declare the variable.
Also,
if(premiumDayMin <0 && premiumNightMin <0)
should probably be changed to
if(premiumDayMin <0 || premiumNightMin <0)
Because you want to make sure that either minutes is not less then zero. You're program should then probably handle this error, because the rest of the program still executes. But maybe you're getting on to that :-P.
I don't recall what I did to stop getting an error message (sorry) but I removed the code if(premiumDayMin <0 && premiumNightMin <0) and replaced it with if(premiumDayMin <= 75 && premiumNightMin <= 100) to stop the code from being redundant. That may have fixed things. I also added another else if to clean the logic up further.

Categories

Resources