So I seem to have put together majority of this program correctly. Ask I skim through I realized I missed something and go back and add it in. Now as I run the program for a final test I realize that it is no longer calculating the miles correctly. I input 500 for example and will get 1 in return for number of miles shipped.
input = JOptionPane.showInputDialog("Enter package weight: ");
weight = Double.parseDouble(input);
input = JOptionPane.showInputDialog("Enter approximate miles package is being shipped: ");
miles = Integer.parseInt(input);
miles = (miles+499)/500;
input = JOptionPane.showInputDialog("Enter number of units shipped: ");
units = Integer.parseInt(input);
I know I am not doing the math correctly in order to find the correct amount charged per unit but what is concerning for now is the miles being shown incorrectly in my output. Any suggestions? Thanks!
Assuming miles is declared as double (if it's not, you should declare it as double so you can assign it a real number). This line
miles = (miles+499)/500;
is making a integer division (int/int = int). To get a double, you must cast it:
miles = (double)(miles+499)/500;
or, as #Vulcan suggested
miles = (miles+499)/500.0; // here 500.0 is a double
It seems like the data type of miles variable is int.Please change it to double and re-run the application.
Also as per ur comment updating the logic :
Let the input you entered is :
double weight = 7; //input
double miles = 550; //input
double unit = 2; //input
double charges =0; //charge of the shipment initialise with 0
charges = (3.70*miles*unit*weight)/(500*7);
System.out.println("The charges is "+charges);
The charges of 1 unit is $3.70 per 7 pound weight per 500 miles.
Also update the existing code :
miles = Integer.parseInt(input); //Use double as conversion
miles = (miles+499)/500; // remove the line
Related
I have written this short code and I want to let users to enter bank balance.
Then in new confirm dialog box they will choose if they want to enter transaction amount.
If "YES" then they enter either positive or negative numbers.
If entered value is negative so program with subtracts transaction amount from bank balance.
If entered value is positive so program will add transaction value to bank balance.
At the end if user selects "No" button in confirm dialog box so program will terminates with results of calculation!
Question:
when I enter numbers for bank balance and transactions so I get wrong answer!
I tried to user while loop and do while but I still get wrong results!
double total = 0;
String blc = JOptionPane.showInputDialog(null,"Enter the balance");
double balance = Double.parseDouble(blc);
int trcsn = JOptionPane.showConfirmDialog(null,"Transaction: ","",JOptionPane.YES_NO_OPTION);
while(trcsn == JOptionPane.YES_OPTION){
String transaction = JOptionPane.showInputDialog(null,"Enter amount:");
double trc = Double.parseDouble(transaction);
trcsn = JOptionPane.showConfirmDialog(null,"Transaction: ","",JOptionPane.YES_NO_OPTION);
if(trc < 0){
total = balance - trc;
}else{
total = balance + trc;
}
}
JOptionPane.showMessageDialog(null,total);
1: I enter 1000 dollars as bank balance.
2: I enter 1050 (positive) as transaction amount.
3: I enter -500 (negative value) as transaction amount for second try.
4: Answer is 1500.00 which is wrong!
1000 + 1050 = 2050.00
2050 - 500 = 1550.00
Answer should be 1550
Why answer is wrong???
In this section:
if(trc < 0){
total = balance - trc;
}else{
total = balance + trc;
}
You are updating your total, but not the balance. From the snippet you made, that remains unchanged.
As pointed out by #Fildor down in the comments below, at the moment you have a bug since you are either adding positive numbers together or else, subracting a negative number (x - (-y) == x + y)). To fix this, simply replace the entire if block with total = balance + trc.
You would need to update your balance to have the same value of total, or else, do without total altogether and use the balance field.
You should do something like the following:
String blc = JOptionPane.showInputDialog(null,"Enter the balance");
double balance = Double.parseDouble(blc);
int trcsn = JOptionPane.showConfirmDialog(null,"Transaction: ","",JOptionPane.YES_NO_OPTION);
while(trcsn == JOptionPane.YES_OPTION){
String transaction = JOptionPane.showInputDialog(null,"Enter amount:");
double trc = Double.parseDouble(transaction);
trcsn = JOptionPane.showConfirmDialog(null,"Transaction: ","",JOptionPane.YES_NO_OPTION);
balance += trc;
}
JOptionPane.showMessageDialog(null,balance);
First, you need to replace your if statement with a += statement. This is because subtracting when trc is negative and adding when trc is positive is equivalent to adding the absolute value of trc every time, which is probably not what you want to do. Second, you need to use 1 variable for balance, and track the changes over time. total is meaningless in the previous code, as it overrides its own value every time that your if statement executes.
double updatedBalance = (trc < 0) ? balance - trc : balance + trc;
total = updatedBalance;
Like the above answer suggests you need to update the balance.
I need to write a program that calculates beverages for an entered amount of money. It was working before but I don't know if NetBeans just got tired of doing stuff or what because it suddenly couldn't get past the inputs. I can't figure out what I need to change to get it to function properly again and I can only assume it's the while loop that it's getting stuck on.
I have tried changing numbers, deleting spaces, altering the while conditions, moving line breaks around, and nothing works. Here is the official question:
Johnny is at the bar and he is going to drink beer.
Write a program that computes how many beers he can buy for money that he has. The program reads the amount and the price of beer, and prints how many beers he can afford. Consider also tax (10%) and tips (20%). Print the result in the following form: If a beer costs $3.25, Johnny can have 3 beers for $15 (he will pay $12.87).
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
double br;
double amt;
double taxPrc;
double bill;
int count = 0;
System.out.printf("enter ur name: ");
String name = sc.nextLine();
System.out.printf("Enter price of beverage: $");
br = sc.nextDouble();
System.out.printf("Enter amt %s has: $", name);
amt = sc.nextDouble();
taxPrc = br * 1.1;
bill = taxPrc * 1.2;
while(bill<amt) {
count++;
bill = taxPrc * 1.2;
}
System.out.printf("if bevergae costs $"+br+", "+name+" can have "+count+" beverges for $"+amt+" (the bill will be $"+bill+").");
System.out.println();
}
My editor isn't showing that there are any problems. The file runs:
"enter ur name (name), Enter price of beverage $(#), Enter amt (name) has $(input number)"
then it just stops showing anything and leaves me on a blank until I stop it.
It's supposed to go on "if beverage costs $X, [name] can have [#] beverages for $[#] (the bill will be $[#])."
I was having an issues trying to get it to display the correct number for the bill less than the initial amount entered when it stopped working.
Just think about this block of code on its own for a bit
bill = taxPrc * 1.2;
while(bill<amt) {
count++;
bill = taxPrc * 1.2;
}
?
What in the while loop changes either bill or amt? Remember, a while loop runs until something in its conditional statement (in this case bill<amt) changes. As nothing in the while loop changes anything in the condition statement, it runs forever.
Your code doesn't change amt at all and just keeps resetting bill to the same value.
I wanted to know why there is an error and how to fix it for my java project.
I have to make exactly same out as these:
What is your annual interest rate as a decimal? (ex: 0.045): .033
How many years will your mortgage be held? 15
What amount of the mortgage did you borrow? 300000
The number 0.033 can be represented as 3.3%
The mortgage amount is $300,000.00
The monthly payment in dollars is $2,115.30
The total payment in over the years in dollars is $380,754.76
The over-payment is $80,754.76 The over-payment as a percentage of
the mortgage is 26.9
And this is what I did on Eclipse;
double annIntRat;
int nOY;
int borrowMor;
int M;
double monthPay;
double mIR;
Scanner scnr = new Scanner(System.in);
// Your code should go below this line
System.out.print("What is your annual interest rate as a decimal? (ex 0.045): ");
annIntRat = scnr.nextDouble();
System.out.print("How many years will your mortgage be held? ");
nOY = scnr.nextInt();
System.out.print("What amount of the mortgage did you borrow? ");
borrowMor = scnr.nextInt();
DecimalFormat df = new DecimalFormat("0.0");
System.out.println("\nThe number "+annIntRat+" can be represented as "+df.format((annIntRat)*100)+"%");
NumberFormat defaultFormat = NumberFormat.getCurrencyInstance();
M=defaultFormat.format(borrowMor); //< Here is the error and tells me to change to String.But if I do so, there will be an error down there for monthPay=.....
System.out.println("The mortgage amount is "+M);
mIR=(annIntRat)/12;
monthPay=(mIR * M)/(1-(1/Math.pow(1+mIR,12*nOY)));
It took me a while to see where you highlighted your error, I would recommend being more explicit with where your errors are.
The 'format' method of NumberFormat you are using returns a type of String, which would explain your error.
The following should do the trick, although you can't be certain that a user is to input an integer...take that in mind.
M = Integer.parseInt(defaultFormat.format(borrowMor));
The DecimalFormat.format(long) method is an inherited method from the NumberFormat class — NumberFormat.format(long). The method returns an instance of String.
So, just use an instance of the String type to store and use the return value of the method:
String borrowMorString = defaultFormat.format(borrowMor);
System.out.println("The mortgage amount is " + borrowMorString);
// …
monthPay = (mIR * borrowMor) / (1 - (1 / Math.pow(1 + mIR, 12 * nOY)));
I'm very new to Java and don't quite understand it all fully, I'm working on a Uni workshop assignment but am having trouble with this particular question.
"Write a program that asks the user to enter how many minutes they have used, and how many texts they have used.
Both inputs should be whole numbers (integers).
The program should then calculate the user’s mobile phone bill, assuming that texts cost 7p and calls 12p.
Should display price of calls, texts and the total bill, both figures added together"
Scanner userInput = new Scanner(System.in);
System.out.println("How many minutes have you used?");
String one = userInput.nextLine();
System.out.println("How many texts have you used?");
String two = userInput.nextLine();
int a = 12;
int b = 7;
System.out.println("The total cost of your minutes is "+one);
System.out.println("The total cost of you texts is "+two);
System.out.println("The total cost of your phone bill is "+one + two);
I have the basic part to the question figured out, but can't figure out why I can't add to the code for it to figure out the price, being 12 p for minutes, and 7p for texts. As well as this I can't get the total cost of the phone bill to add together correctly. I did earlier and I know it's very easy, but I've completely forgotten how to do it.
I know I need to be able to understand a scanner better, but I did the previous tasks easy enough but this has really stumped me tbh. Do I need to rename the scanner, but when I change the name of the integer line to something like "totalCostOfTexts/Minutes etc" it either says it has already been defined, or is missing some kind of symbol.
Any feedback is appreciated.
I add the code :
int = userInput = minutes * 12:
As that's what is used in the previous part of a similar question, but all the feedback I get is that it is not a statement, so it can't process. I'm really struggling with this tbh.
Following code will work for you
Scanner userInput = new Scanner(System.in);
System.out.println("How many minutes have you used?");
int one = userInput.nextInt();
System.out.println("How many texts have you used?");
int two = userInput.nextInt();
int a = 12; //don't use such variable names
int b = 7;
int minute_bill=12*a; //see the variable,will make things easier to review
int text_bill=7*b;
int result=minute_bill+text_bill;
System.out.println("The total cost of your minutes is "+minute_bill);
System.out.println("The total cost of you texts is "+ text_bill);
System.out.println("The total cost of your phone bill is "+result);
and also
You can use Scanner's nextInt() method for taking integer input
from console.
Don't use such variable names like a,b etc. define them according to the attribute whose value you are storing in them (see above minute_bill and text_bill are making the code clean and easy to review)
And if you are bound to get String value from console,but want to convert entered value to Integer later on, then you can do it like following code
String mystring=userInput.nextLine(); //userInput is user Scanner's object
int num=Integer.parseInt(mystring);
I think this is what you want to do...
Scanner userInput = new Scanner(System.in);
System.out.println("How many minutes have you used?");
int one = Integer.valueOf(userInput.nextLine());
System.out.println("How many texts have you used?");
int two= Integer.valueOf(userInput.nextLine());
int a = 12;
int b = 7;
System.out.println("The total cost of your minutes is "+ (one * 12);
System.out.println("The total cost of you texts is "+ (two * 7));
System.out.println("The total cost of your phone bill is "+ ((one * 12) + (two * 7));
This question already has answers here:
min change greedy algorithm in java
(2 answers)
Closed 8 years ago.
I have a cashregister program that inputs purchases and payment and outputs the change due. i need it to not give just an amount but what particular coins/dollars user should get back. heres two methods i have
public void recordPurchase()
{
System.out.print("Enter total purchase price or negative number to end: ");
double input = keyboard.nextDouble();
while(input > 0)
{
purchase = purchase + input;
System.out.print("Enter total purchase price or negative number to end: ");
input = keyboard.nextDouble();
}
}
public double giveChange(Money moneyTypes)
{
double change = payment - purchase;
purchase = 0;
payment = 0;
//computes change rounding to two decimal places
change = (double)(Math.round(change*100))/100;
return change;
}
I need to output what coins/dollars person should get back. i have the money types saved in an array called moneyTypes. for example if the change due is $1.06 it would output you receive a dollar nickel and penny.
any advice would help. Thanks! if you need to see more of the code let me know
I'll give you an advice how to do it, not a solution.
Make a list of possible coin/note values.
Then from the biggest to lowest, compute how many times it fits into the remainder, and subtract this amount of money from the value. Make a note of the number of coins/notes.
This way, you will get the numbers you need.
count = Math.floor(remainder/coinValue) might help you.