I just started coding in java and I am working on a change machine-esk program. I know It can be condensed but Its part of the constraints.
It keeps out putting random change owed and quarter count...
import java.util.Scanner;
public class Change {
public static void main(String[] args) {
double costVar, paidVar, amountOwed;//user defined
//defining the vale of US coins
final double quarterCoin = 0.25;
final double dimeCoin = 0.10;
final double nickelCoin = 0.05;
final double pennyCoin = 0.01;
//Variable for math stuff
double quarterAmountdec, dimeAmountdec, nickelAmountdec, pennyAmountdec;
short quarterAmountfin, dimeAmountfin, nickelAmountfin, pennyAmountfin;
Scanner keyboard = new Scanner(System.in);
//ask the user to input costs and amount payed (assuming the amount paid is > or = the cost of the item)
System.out.println("Enter Item Cost: ");
costVar=keyboard.nextDouble();
System.out.println("Enter Amount Paid: ");
paidVar=keyboard.nextDouble();
amountOwed = paidVar - costVar;//math for the changed owed
System.out.println("\nChange Owed: $" +amountOwed++);//displaying how much change the machine owes
//math to calculate the coins owed (involves intentional loss of accuracy
quarterAmountdec = amountOwed / quarterCoin;
quarterAmountfin = (short)quarterAmountdec;
//outputs coins owed
System.out.println("Quarters: " +quarterAmountfin++ );
}
}
Output:
Enter Item Cost:
2.34
Enter Amount Paid:
6.89
Change Owed: $4.55
Quarters: 22
The following line alters the amount owed after printing
System.out.println("\nChange Owed: $" +amountOwed++);
Thus when printing the amount owed looks fine, but internally the value is changed. I am personally unsure of the behaviour of calling ++ on a double, however I recommend removing the ++ and re-running your code.
Related
I am creating my first java program for the class. The purpose of the program is to calculate interest for deposit for year one and year two. My issue comes when the code outputs the final totals. The last two lines are supposed to use System.out.printf(). I keep getting the error Exception in thread "main" java.util.UnknownFormatConversionException: Conversion = 'i'. How do I correct this?
public static void main(String... args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Hello World!");
//declares variables
double interest = 0;
double balance = 0;
double deposit = 0;
double secondYearBalance = 0;
double secondYearInterest = 0;
//displays welcome message
System.out.println("Welcome to George's Interest Calculator");
//prompts user for input
System.out.println("Please enter your initial deposit:");
deposit = keyboard.nextInt();
//Finds outs interest interest earned on deposit
interest = deposit * TAXRATE;
//Finds out the amount of the balance
balance = deposit + interest;
//finds out second year balance
secondYearInterest = balance * TAXRATE;
secondYearBalance = secondYearInterest + balance;
//Outputs totals
System.out.printf("Your balance after one year with a 4.9% interest rate is $%7.2f %n", balance);
System.out.printf("Your balance after two years with a 4.9% interest rate is $%7.2f %n", secondYearBalance);
System.out.println();
}
The % symbol is used in a printf string for 'put a variable here'.
That's problematic when you write 4.9% interest rate because java thinks that % i is you saying: "a variable goes here". The fix is trivial; a double % is how you write a single percent. Thus:
System.out.printf("Your balance after one year with a 4.9%% interest rate is $%7.2f %n", balance);
Assignment: Variables
This program prompts the user to enter a temperature between -58°F and
41°F and a wind speed greater than or equal to 2 then displays then
displays the wind-chill temperature.
// Imports util.Scanner
import java.util.Scanner;
public class Windchill {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
// Tempurature
double temperature = input.nextDouble();
// Windspeed
double speed = input.nextDouble();
// Compute the wind chill tempurature
double windChill = 35.74 + 0.6215 * temperature -
35.75 * Math.pow(speed,
0.16) + 0.4275 * temperature *
Math.pow(speed, 0.16);
// Prompt the user to enter a temperature between -58F and 41F.
System.out.print("Enter the temperature in Fahrenheit " +
"between -58\u00b0F and 41\u00b0F: ");
// Prompt the user to enter the wind speed greter than or equal to 2.
System.out.print("Enter the wind speed (>= 2) in miles per hour: ");
// Display result
System.out.println("The wind chill tempurature is " + windChill);
}
}
This seems to be a school assignment. However, it seems like you have already completed the bulk of the work. Congratulations! Now, I feel like the issue here can be solved by explaining why your program does not work if "the doubles are on top". I hope that my answer can help you better understand the way java interprets your code!
Without further ado, programming languages of all types have variables. Java is no different. For example...
double number = 0.0; // Java variable declaration
number = 0.0 # Python variable declaration
var number = 0.0 // JavaScript variable declaration
Your code is going to be executed from the top down. An illustration of this would look like the following.
int money = 0;
System.out.println(money);
money = 10;
System.out.println(money);
money = 9000;
System.out.println("I have over " + money);
This will output
0
10
I have over 9000
However, if you wrote this code like the following
System.out.println(money);
int money = 0;
You will get an error! This is because the execution has not seen that money is even a thing yet! This would be like brushing your teeth without a tooth brush. You can't because you don't have a brush.
Therefore, the same applies to your program.
public static void main(String[] args) {
double temperature = input.nextDouble();
Scanner input = new Scanner(System.in);
// Prompt the user to enter a temperature between -58F and 41F.
System.out.print("Enter the temperature in Fahrenheit " +
"between -58\u00b0F and 41\u00b0F: ");
// Tempurature
// Prompt the user to enter the wind speed greter than or equal to 2.
System.out.print("Enter the wind speed (>= 2) in miles per hour: ");
// Windspeed
double speed = input.nextDouble();
// Compute the wind chill tempurature
double windChill = 35.74 + 0.6215 * temperature -
35.75 * Math.pow(speed,
0.16) + 0.4275 * temperature *
Math.pow(speed, 0.16);
// Display result
System.out.println("The wind chill tempurature is " + windChill);
}
Notice temperature above the scanner line. Input is a object you create to read in that double. If you try to use this before you create your input object the program has no idea what that input object is!
Just rearrange the code like below
// Imports util.Scanner
import java.util.Scanner;
public class Windchill {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
// Prompt the user to enter a temperature between -58F and 41F.
System.out.print("Enter the temperature in Fahrenheit " +
"between -58\u00b0F and 41\u00b0F: ");
// Tempurature
double temperature = input.nextDouble();
// Prompt the user to enter the wind speed greter than or equal to 2.
System.out.print("Enter the wind speed (>= 2) in miles per hour: ");
// Windspeed
double speed = input.nextDouble();
// Compute the wind chill tempurature
double windChill = 35.74 + 0.6215 * temperature -
35.75 * Math.pow(speed,
0.16) + 0.4275 * temperature *
Math.pow(speed, 0.16);
// Display result
System.out.println("The wind chill tempurature is " + windChill);
}
}
but there is no problem related to double, :)
Thanks everyone. I got it.
/* Assignment: Variables
This program prompts the user to enter a temperature between -58°F and 41°F
and a wind speed greater than or equal to 2 then displays then displays the
wind-chill tempurature.
*/
// Imports util.Scanner
import java.util.Scanner;
public class Windchill {
public static void main(String[] args) {
// Declare variables
double temperature;
double windspeed;
double wind_chill;
// Create a Scanner object to read input
Scanner input = new Scanner(System.in);
// Prompt the user to enter a temperature between -58F and 41F.
System.out.print("Enter the temperature in Fahrenheit " +
"between -58\u00b0F and 41\u00b0F: ");
temperature = input.nextDouble();
// Prompt the user to enter the wind speed greter than or equal to 2.
System.out.print("Enter the wind speed (>= 2) in miles per hour: ");
windspeed = input.nextDouble();
// Display result
wind_chill = 35.74 + 0.6215 * temperature -
35.75 * Math.pow(windspeed, 0.16) +
0.4275 * temperature * Math.pow(windspeed, 0.16);
System.out.println("The wind chill temprature is " + wind_chill);
}
}
I'm trying to add together the sum of the iterations of a for loop. This is what I have so far.
import java.util.Scanner;
public class Pennies
{
public static void main (String [] args)
{
double amount; //To hold the amount of pennies per day
double days; //To hold the days user saved.
double total;
System.out.println("I will display a table of salary if you're paid every day in pennies and it doubles every day.");
Scanner keyboard = new Scanner(System.in);
System.out.print("How many days do you wish to save for?");
days = keyboard.nextDouble();
//Display the table
System.out.print("Day \t Salary \n");
for (amount = 1; amount <= days; amount++)
{
total = amount * .01 * amount;
System.out.println(amount + "\t \t $" + total);
}
}
}
Any help would be greatly appreciated!
In order to keep on adding the salary for each day and keeping the track of total for each day (as I get it from your statement), you can change:-
total = amount * .01 * amount;
to
total += amount * .01 * amount; // total = total + (amount*0.01*amount)
which(when not printing each day information separately) can be simplified as:-
total = amount * .01 * amount * days;
I compiled your code and noticed that your numbers were off. Assuming that you want the first day's pay to be one penny, and for it to double every following day, here's what I came up with. It's hard to tell if this is exactly what you want since you didn't actually ask a question, so let me know if this is what you're looking for.
public static void main(String[] args) {
System.out
.println("I will display a table of salary if you're paid every day in pennies and it doubles every day.");
Scanner keyboard = new Scanner(System.in);
System.out.print("How many days do you wish to save for?");
double days = keyboard.nextDouble();
// Display the table
System.out.print("Day \t Salary \n");
double pay = 0.01;
double totalPay = 0.0;
for (int i = 1; i <= days; i++) {
System.out.println(i + "\t \t $" + pay);
totalPay += pay;
pay *= 2;
}
System.out.println("Total Pay \t $" + totalPay);
keyboard.close();
}
You're originally doing total = amount*0.1*amount, which won't give you what you want. You're confusing squaring amount with simply doubling it.
Edit: Also consider changing days to an int. I don't see any reason why it should be a double
Ok so I am working on a program that involves loans and gives information to the user about loans from what the user inputs.
The purpose of this program I am writing is for the user to be asked to input a loan amount and the number of years that they have to pay it off. Once the user has given this information, the program will take the loan amount and number of years and tell the user the annual interest rate, monthly payment and the total amount.
ALSO, if the user enters a loan amount of -1, the program is supposed to terminate.
Below is my code thus far:
package Loans;
import java.util.Scanner;
public class Loans {
public static void main(String[] args) {
Scanner input = new Scanner (System.in);
double monthlyInterestRate;
double annualInterestRate;
double monthlyPayment;
double total;
double numberOfYears;
double loanAmount;
System.out.println("This program will compute the monthly payments and total payments for a loan amount on interest rates starting at 5%, incrementing by 1/8th percent up to 8%.");
//Formula to Calculate Monthly Interest Rate:
monthlyInterestRate = (annualInterestRate/1200);
//Formula to Calculate Monthly Payment:
monthlyPayment = (loanAmount*monthlyInterestRate);
//Formula To Calculate Annual Interest Rate:
annualInterestRate = (1-(Math.pow(1/(1 + monthlyInterestRate), numberOfYears * 12)));
//Formula To Calculate The Total Payment:
total = (monthlyPayment*numberOfYears*12);
while(true)
{
System.out.println("Please enter in the loan amount.");
double loanAmount = input.nextDouble();
System.out.println("Please enter in the number of years.");
double numberOfYears = input.nextDouble();
System.out.println("Interest Rate: " + annualInterestRate);
System.out.println("Monthly Payment: " + monthlyPayment);
System.out.println("Total Payment: " + total);
}
}
}
This does not compile and I'm not sure why. (Again, I'm a beginner)
The errors I am receiving are on the line that reads "double loanAmount = input.nextDouble();" AND the line that reads "double numberOfYears = input.nextDouble();".
The error for the first line says, "Duplicate local variable loanAmount".
The error for the second line says, "Multiple markers at this line
- Line breakpoint:Loans [line: 39] -
main(String[])
- Duplicate local variable numberOfYears"
Any feedback is appreciated.
The error you get is pretty much self explanatory. You have defined both "loanAmount" and "numberOfYears" two times in main. Either rename them or declare them only once.
If you are a beginner in coding I would recommend you use an IDE like Eclipse or Netbeans. They will point out compilation errors along with suggestions on how to fix them.
Easy enough to fix. So the issue is that in this segment:
System.out.println("Please enter in the loan amount.");
double loanAmount = input.nextDouble();
System.out.println("Please enter in the number of years.");
double numberOfYears = input.nextDouble();
You are re-defining your double variables loanAmount and numberOfYears, which is going to cause an error. Take out the "double" in both lines where they are used.
The other change you need to make is to intialize these variables at the top of your code. Change the lines where you initialize all of your double variables and set them equal to 0, for example:
double annualInterestRate = 0;
double numberOfYears = 0;
double loanAmount = 0;
When a variable has a call in a program, it must first be initialized. It doesn't matter what it's initialized to, since its end value will be determined by the program's actions, but it absolutely needs to be initialized at some point.
I made exactly these changes and the program compiled successfully.
Hope this helps!
I am working on an assignment for school and I have a basic program already that calculates the total cost of a trip by asking the total mileage, average mpg of car, and cost per gallon of gas. This works great but I also need to add a few more items and I am unsure of how to do so. First I need to include a menu of some sort giving the option to either calculate the trip cost or exit the program. Next I need to incorporate somewhere in the program a bit asking if the user wants an oil change or not and then based on the answer adding this to the total.
import java.util.Scanner;
public class GasCalculator {
public static void main (String args[])
{
Scanner scan = new Scanner(System.in);
System.out.println("How many miles do you plan to travel?");
int miles = scan.nextInt();
System.out.println("So you will drive " + miles +" miles.");
System.out.println("What is the price of gas?");
double gas = scan.nextDouble();
System.out.println("Ok, so gas costs $" + gas +" per gallon.");
System.out.println("What is the average MPG of your car? Use the nearest whole number.");
int mpg = scan.nextInt();
System.out.println("So, you get " + mpg +" miles per gallon.");
System.out.println("Would you like an oil change? Enter Y or N");
double cost = (miles / mpg * gas + oil);
System.out.println("Below is your total cost");
System.out.println(String.format("Your trip will cost $" + cost + "."));
}
}
As you can see I added a little bit asking if they want an oil change. My vision of doing it would be to create a variable for either the y or n answer and then an if else statement based on whether y or n. If y it will add 39.99 to a new variable "oil". If n it will make the variable 0. Oil has been incorporated into the final equation regardless of it's value for ease.
I am not looking for anyone to do my assignment for me. I guess I am looking to see what this would look like or if anyone has any input as far as how I should tackle this. Thank you for any help you can provide!
First I need to include a menu of some sort giving the option to
either calculate the trip cost or exit the program.
You can use a switch statement.
//ask for user to enter 0 to exit, 1 to calculate the trip
switch(answer) {
case 0 : System.exit(0);
break;
case 1 : //calculate cost trip here
break;
default : System.exit(0);
}
Next I need to incorporate somewhere in the program a bit asking if
the user wants an oil change or not and then based on the answer
adding this to the total
Well you can get the value of the user with your Scanner object like you did and write an if statement to check this value.
System.out.println("Would you like an oil change? Enter Y or N");
//here get the value of the user using your scanner object
double oil = 0;
if(/*test if value is equals to y*/)
oil += 39.99;
Hints :
to avoid testing if the value is "y" or "Y", use the method equalsIgnoreCase of the String class.
when this will works you can wrap the functionnality of calculating the trip cost in a method and call this method in the case 1 of the switch statement.
Edit
import java.util.Scanner;
public class GasCalculator {
public static void main (String args[])
{
double total = 0;
Scanner scan = new Scanner(System.in);
System.out.println("How many miles do you plan to travel?");
int miles = scan.nextInt();
System.out.println("So you will drive " + miles +" miles.");
System.out.println("What is the price of gas?");
double gas = scan.nextDouble();
System.out.println("Ok, so gas costs $" + gas +" per gallon.");
System.out.println("What is the average MPG of your car? Use the nearest whole number.");
int mpg = scan.nextInt();
System.out.println("So, you get " + mpg +" miles per gallon.");
System.out.println("Would you like an oil change? Enter Y or N");
char oil = scan.next().charAt(0);
if (Character.toUpperCase(oil) == 'Y'){
System.out.println("Cost of oil change id 39.99);
System.out.println("39.99 will be added to your total cost");
total += 39.99;
}
double cost = (miles / mpg * gas);
total += cost;
String menu = "Pick a menu option: \n"
+ "1. Calculate total \n"
+ "2. exit";
System.out.println(menu);
int choice = scan.nextInt();
if (choice == 1){
System.out.println("Below is your total cost");
System.out.println(String.format("Your trip will cost $" + total + "."));
} else {
System.exit(0);
}
}
}
You can implement exit option like this:
System.out.println("Choose your desired option:\n1)Calculate Trip Cost\n2)Exit");
int answer = scan.nextInt();
if (answer==1){
// the rest of your program
System.out.println("How many miles do you plan to travel?");
int miles = scan.nextInt();
System.out.println("So you will drive " + miles +" miles.");
System.out.println("What is the price of gas?");
double gas = scan.nextDouble();
System.out.println("Ok, so gas costs $" + gas +" per gallon.");
System.out.println("What is the average MPG of your car? Use the nearest whole number.");
int mpg = scan.nextInt();
System.out.println("So, you get " + mpg +" miles per gallon.");
System.out.println("Would you like an oil change? Enter Y or N");
double cost = (miles / mpg * gas + oil);
System.out.println("Below is your total cost");
System.out.println(String.format("Your trip will cost $" + cost + "."));
}