So I'm writing a program for an invoice calculator for class.
However, I need to code interest for every 30 days for 10%
total * interest rate (0.10) if 30 days
So, lets say they need to pay interest for 60 days. so twice
total * interest rate --> with another interest on top of that and so on
another example:
so for the program it depends on the date since last invoice. if it is 30 daysyou will be charged 10% interest. if it is 60 days you will be charged another 10% interest on top of that. if it is 90 days you will be charged another 10% interest on top of that. and so on
Do I use a for loop?
public static void main(String[] args) {
// TODO Auto-generated method stub
DecimalFormat formatter = new DecimalFormat("#0.00");
Scanner input = new Scanner (System.in);
double purchase, invoiceAmount, tax, interest, total = 0;
int validYear, validMonth, validDay, invoiceYear, invoiceMonth, invoiceDay;
int daysdiff;
/* double invoiceAmount = 0;
double tax = 0;
double total = 0;*/
System.out.println("Welcome to the Invoice Calculator\n");
System.out.print("Enter the number of minutes you wish to purchase: ");
purchase = input.nextDouble();
System.out.println("Today's Date");
System.out.print ("Year: ");
validYear = input.nextInt ();
while(validYear < 1950 || validYear > 2016){
System.out.print ("Invalid!!\nEnter Year: " );
validYear = input.nextInt();
}
System.out.print ("Month: ");
validMonth = input.nextInt ();
while(validMonth < 1 || validMonth > 12){
System.out.print ("Invalid!!\nEnter Month: " );
validMonth = input.nextInt();
}
System.out.print ("Day: ");
validDay = input.nextInt ();
while(validDay < 1 || validDay > 30){
System.out.print ("Invalid!!\nEnter day: " );
validDay = input.nextInt();
}
System.out.println("Invoice Date");
System.out.print ("Year: ");
invoiceYear = input.nextInt ();
while(validYear < 1950 || validYear > 2016){
System.out.print ("Invalid!!\nEnter year " );
invoiceYear = input.nextInt();
}
System.out.print ("Month: ");
invoiceMonth = input.nextInt ();
while(invoiceMonth < 1 || invoiceMonth > 12){
System.out.print ("Invalid!!\nEnter month: " );
invoiceMonth = input.nextInt();
}
System.out.print ("Day: ");
invoiceDay = input.nextInt ();
while(invoiceDay < 1 || invoiceDay > 30){
System.out.print ("Invalid!!\nEnter day: " );
invoiceDay = input.nextInt();
}
System.out.println("\nToday's Date is: " + validYear + "/" + validMonth + "/" + validDay);
System.out.println("Invoice Date is: " + invoiceYear + "/" + invoiceMonth + "/" + invoiceDay + "\n");
invoiceAmount = (purchase * 0.02) +5;
tax = (invoiceAmount * 0.13);
total = (invoiceAmount + tax);
interest = (total * 0.10);
// The number of days since invoice date:
daysdiff = (validYear - invoiceYear) *365 + (validMonth - invoiceMonth) *30 +(validDay - invoiceDay);
System.out.print("The number of days since invoice date is: " + daysdiff);
System.out.print("\nInvoice Amount: $");
System.out.println(formatter.format(invoiceAmount));
System.out.print("Tax : $");
System.out.println(formatter.format(tax));
System.out.print("Interest : $");
System.out.println(formatter.format(interest));
System.out.print("TOTAL : $");
System.out.println(formatter.format(total));
}
}
Thank you
if you want to tax 10% for every 30days you'd need something like this.
public class test {
public static void main(String[] args) {
double total = 100.0;
int numDays = 90;
//gets how many times your invoice days goes into 30
int taxNum = numDays / 30;
//decreases total according to your tax
for( int i = 0; i < taxNum; i++ ){
total -= total * .1;
}
System.out.println(total);
}
}
Related
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.
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.
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.
I have a project in mind however there are a few basics I need to master before I can proceed. Here's the issue I'm trying to call a function from main in java but I can't get it to compile. I have read the feedback and I went with using a switch to call each function. I always get "error can't find symbol". I've made a few changes here and there trying to get it to run. Once again I feel like I'm lacking something very fundamental and it's preventing me from getting this to work. Any ideas
import java.util.*;
import java.lang.*;
import java.io.*;
class Practice {
static void wagecalc() {
Scanner input = new Scanner(System.in);
System.out.println("Input pay per hour:");
int a = input.nextInt();
int b;
System.out.println("Input hours worked:");
b = input.nextInt();
int c;
System.out.println("Input days worked:");
c = input.nextInt();
int gross = a * b * c;
System.out.println("Your gross pay is:" + gross);
// Determining tax rate//
if (gross < 10000) {
int taxrate = gross * 10 / 100;
System.out.println("Your tax rate is 10%:/n");
int total = gross - taxrate;
System.out.println("Your net pay is:" + total + "/n");
}
else if (gross > 10000 || gross <= 30000) {
int taxrate = gross * 15 / 100;
System.out.println("Your tax rate is 15%:/n");
int total = gross - taxrate;
System.out.println("Your net pay is:" + total + "/n");
}
else if (gross >= 30000 || gross <= 70000) {
int taxrate = gross * 20 / 100;
System.out.println("Your tax rate is 20%:/n");
int total = gross - taxrate;
System.out.println("Your net pay is:" + total + "/n");
}
else if (gross > 70000) {
int taxrate = gross * 25 / 100;
System.out.println("Your tax rate is 25%:/n");
int total = gross - taxrate;
System.out.println("Your net pay is:" + total + "/n");
}
}
static void autocalc() {
Scanner input = new Scanner(System.in);
// Declaring the variables as an integer//
int auto;
int loan;
int interest;
int mnydwn;
int pymnt;
int year;
int month = 12;
int tap;
int term = year * month;
int spec;
System.out.println("Please enter the following information for your car loan:/n");
System.out.println("Please enter the amount of the vehicle you wish to purchase:/n");
auto = input.nextInt();
System.out.println("Please enter the amount of money you wish to put down:/n");
mnydwn = input.nextInt();
System.out.println("Please enter the interest rate:/n");
interest = input.nextInt();
System.out.println("Please enter the term of the loan (years):/n");
year = input.nextInt();
System.out.println("Processing......../n");
System.out.println("Processing............");
// Calculations//
loan = auto - mnydwn;
int intamt = loan * interest;
tap = loan + intamt;
pymnt = tap / term;
// Display//
System.out.println("Process...Complete./n");
System.out.println("Car amount:" + auto);
System.out.println("Loan recieved:" + loan);
System.out.println("Interest rate:" + interest);
// if statement for proper output of year//
if (year == 1) {
System.out.println("Your monthly payments will be" + pymnt + "for a" + year + "year" + term + "months.");
} else if (year > 1) {
System.out.println("Your monthly payments will be" + pymnt + "for" + year + "years" + term + "months.");
}
System.out.println("Total amount paid at the end of the term" + tap);
}
public static void main(String[] args) throws java.lang.Exception {
// User input//
Scanner input = new Scanner(System.in);
int count = 0; // Count for the while loop//
// Instructions on how to begin interface//
System.out.println("Hi!/n");
System.out.println("...Thanks for using D Anomaly's Finance calculator!!/n");
System.out.println("Please choose one of the following:/n");
System.out.println(" 1. Wages:/n");
System.out.println(" 2. Auto Loan:/n");
// System.out.println(" 3. Home Loan:/n");//
System.out.println("Choose 1-3");
int calc = input.nextInt();
switch (calc) {
case 1:
wagecalc();
break;
case 2:
autolcalc();
break;
case 3: // homecalc();//
break;
if (calc >= 4) {
System.out.println(" Invalid entry!!!/n");
System.out.println("Please try again:");
break;
}
}
}
}
There are a few problems here, including the following:
1.
public void wageinformation(int gross) needs to be declared static if you want to call it from main()
2.
You are calculating int gross = a * b * c right after you have received it as a parameter.
3.
You have (or had in the initial version of this post) several extra braces.
4.
The deduction and total variables are never declared within the wageinformation() method.
I would strongly suggest working through some online Java tutorials if you are looking to improve your skills.
I am having an issue getting the sum of the integers in my array AND an issue getting the product of an integer * 1.5. My code below could be completely off as I am new to Java and have been at this for hours and hours. The purpose of the program is to enter the number of hours worked, each day, for 5 days. With that, and the pay rate, you're supposed to output the average hours worked, total hours, and total pay. The pay should also include overtime if there is any. Any help would be appreciated.
String name;
String id;
int payRate;
int[] hours = new int[5];
int avgHours;
int totalPay;
int totalHours = 0;
int counter;
int overTime = 0;
//housekeeping
System.out.print("Enter the Employee's name: ");
inputString = input.readLine();
name = inputString;
System.out.print("Enter the Employee's ID: ");
inputString = input.readLine();
id = inputString;
System.out.print("Enter the Employee's pay rate: ");
inputString = input.readLine();
payRate = Integer.parseInt(inputString);
//hoursPay
counter = 0;
for(hours[counter] = 0; counter < 5; counter++)
{
System.out.print("How many hours did the employee work? ");
inputString = input.readLine();
hours[counter] = Integer.parseInt(inputString);
}//endfor
for(totalHours = 0; counter < 5; hours[counter]++);
{
totalHours += hours[counter];
if(totalHours > 40)
{
overTime = payRate + (payRate / 2);
}//endif
}//endwhile
//print
if(counter == 5)
{
System.out.println(name + " " + id + " $" + payRate + "/hour" );
avgHours = totalHours / counter;
totalPay = totalHours * payRate + overTime;
System.out.println...
System.out.println...
System.out.println...
#bp_1,
I re-do all the code again and pasted it below. It WORKS. There was some fundamental error you making while coding. Compare your code with mine and you will see the difference.
String name;
String id;
int payRate;
int[] hours = new int[5];
int avgHours;
int totalPay;
int totalHours = 0;
int counter;
int overTime = 0;
Scanner input = new Scanner(System.in);
//housekeeping
System.out.print("Enter the Employee's name: ");
String inputString = input.nextLine();
name = inputString;
System.out.print("Enter the Employee's ID: ");
inputString = input.nextLine();
id = inputString;
System.out.print("Enter the Employee's pay rate: ");
inputString = input.nextLine();
payRate = Integer.parseInt(inputString);
//hoursPay
counter = 0;
for (hours[counter] = 0; counter < 5; counter++) {
System.out.print("How many hours did the employee work? ");
inputString = input.nextLine();
hours[counter] = Integer.parseInt(inputString);
}//endfor
counter = 0;// reset counter here
for (totalHours = 0; counter < 5; counter++) {
totalHours += hours[counter];
if (totalHours > 40) {
overTime = payRate + (payRate / 2);
}//endif
}//end of for loop
if (counter == 5) {
System.out.println(name + " " + id + " $" + payRate + "/hour");
avgHours = totalHours / counter;
totalPay = totalHours * payRate + overTime;
System.out.println("Average Hours: " + avgHours);
System.out.println("Total pay: " + totalPay);
System.out.println("Total Hours: " + totalHours);
System.out.println("Overtime ($): " + overTime);
}//end of if
In place of
for(totalHours = 0; counter < 5; hours[counter]++);
write
for(counter = 0; counter < 5; counter++)
semicolon removed.
counter incremented instead of hours[counter]