What is wrong with the formula in my code? [duplicate] - java

This question already has answers here:
Why double width = 50/110000; the output is 0.000000000000000?
(3 answers)
Closed 9 years ago.
We've been set a task to calculate user input. My code compiles, however when I test it my output for the refund is always 0 :(
Users are meant to enter their distance and self contribution when prompted, but what exactly is wrong with my formula for refund? Can anybody shed some light on this for me?
import java.util.*;
public final class UserCalc {`
public static void main(String[] args) {
Scanner scanner = new Scanner(System. in );`
System.out.print("Please enter the distance ");
int distance = scanner.nextInt();
System.out.print("Please enter the percentage of self contribution ");
int selfcon = scanner.nextInt();
int trainprice = (75 + (2 / 10)) * distance;
int carprice = (26 + (7 / 10)) * distance;
int refund = (Math.min(trainprice, carprice)) * ((100 - selfcon) / 100);
System.out.print("You get a refund of " + refund + " pounds");
int age = scanner.nextInt();
}
}

Because result of ((100 - selfcon)/100) is always zero and you works with integers you should use float or double.

You are using integer arithmetic rather than floating point arithmetic, so expressions like 2/10 evaluate to 0.

double distance = scanner.nextDouble();
System.out.print("Please enter the percentage of self contribution ");
double selfcon = scanner.nextDouble();
double trainprice = (75 + (2 / 10)) * distance;
double carprice = (26 + (7 / 10)) * distance;
doulbe refund = (Math.min(trainprice, carprice)) * ((100 - selfcon) / 100);
System.out.print("You get a refund of " + refund + " pounds");
int age = scanner.nextInt();

Related

BMI Calculator Java incorrect output [duplicate]

This question already has answers here:
Int division: Why is the result of 1/3 == 0?
(19 answers)
Closed 5 years ago.
I am trying to code a basic command line BMI Calculator in Java and for some reason every time I run the code and enter my height and weight, 0 is outputted. Please help me understand where I have made a mistake.
import java.util.Scanner;
public class Chap2 {
public static void main(String[] args){
Scanner reader = new Scanner(System.in);
System.out.println("Enter your height in inches: ");
int myHeight = reader.nextInt();
System.out.println("Enter your weight in lbs: ");
int myWeight = reader.nextInt();
int Bmi = (myWeight/myHeight/myHeight)*703;
System.out.println("Your BMI is " + Bmi + ".");
}
}
And my output is as follows:
Enter your height in inches:
68
Enter your weight in lbs:
180
Your BMI is 0.
You are dividing int with int, thus the result is a rounded int.
Cast to double before calculation to get exact results.
double bmi = ((double) myWeight / myHeight / myHeight) * 703;

I'm not sure how to round this properly in my Java code

I'm fairly new to Java, and I've recently written a code that calculates how much change you would need for x amount of money payed for a y priced item. It works well; my only issue is that whenever there is not any change owed in the hundredths place (ex: $4.60), it will round down to the tenths place ($4.6).
If anybody knows how to fix this, I would be very grateful. I have the code posted below.
class Main {
public static void main(String[] args) throws IOException {
Scanner scan = new Scanner(System.in);
double x;
double y;
double z;
System.out.print("Enter the price of the product: $");
x = scan.nextDouble();
System.out.print("Enter what you payed with: $");
y = scan.nextDouble();
z = (int)Math.round(100*(y-x));
System.out.print("Change Owed: $");
System.out.println((z)/100);
int q = (int)(z/25);
int d = (int)((z%25/10));
int n = (int)((z%25%10/5));
int p = (int)(z%25%10%5);
System.out.println("Quarters: " + q);
System.out.println("Dimes: " + d);
System.out.println("Nickels: " + n);
System.out.println("Pennies: " + p);
}
}
Edit: Thank you to everyone that answered my question! I ended up going with DecimalFormat to solve it, and now it works great.
You can call something like this:
String.format("%.2f", i);
So in your case:
...
System.out.print("Change Owed: $");
System.out.println((String.format("%.2f", z)/100));
...
String.format() is useful whenever you want to round it to certain significant figures. In this case "f" stands for float.
This behavior is expected. You do not want numbers to carry trailing zeroes.
You can use DecimalFormat for representing them as a String with a trailing zero, rounded to two digits.
Example:
DecimalFormat df = new DecimalFormat("#0.00");
double d = 4.7d;
System.out.println(df.format(d));
d = 5.678d;
System.out.println(df.format(d));
Output:
4.70
5.68
You can also add your currency sign to the DecimalFormat:
DecimalFormat df = new DecimalFormat("$#0.00");
Output with currency sign:
$4.70
$5.68
EDIT:
You can even tell DecimalFormat how to round your number by setting the RoundingMode through df.setRoundingMode(RoundingMode.UP);
The String.format() method is my personal preference. For example:
float z;
System.out.println(String.format("Change Owed: $%.2f", (float) ((z) / 100)));
%.2f will round any float ('f' stands for float) off to 2 decimal places, by changing the number before the 'f' you change how many decimal points you round to. Eg:
//3 decimal points
System.out.println(String.format("Change Owed: $%.3f", (float) ((z) / 100)));
//4 decimal points
System.out.println(String.format("Change Owed: $%.4f", (float) ((z) / 100)));
// and so forth...
You may want to do some reading into String.format() if you are starting out with Java. It is a very powerful and useful method.
From what I understand:
public static void main(String[] args) throws IOException {
Scanner scan = new Scanner(System.in);
double x;
double y;
double z;
System.out.print("Enter the price of the product: $");
x = scan.nextDouble();
System.out.print("Enter what you payed with: $");
y = scan.nextDouble();
z = (int) Math.round(100 * (y - x));
System.out.println(String.format("Change Owed: $%.2f", (float) ((z) / 100)));
int q = (int) (z / 25);
int d = (int) ((z % 25 / 10));
int n = (int) ((z % 25 % 10 / 5));
int p = (int) (z % 25 % 10 % 5);
System.out.println("Quarters: " + q);
System.out.println("Dimes: " + d);
System.out.println("Nickels: " + n);
System.out.println("Pennies: " + p);
}
All the best for your future projects!

Java Skipping last variable [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I have been trying to make a basic calculator that calculates the mean of 9 numbers. The problem is it always skips the last line.
My code:
/* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package avarage.calc;
import java.util.Scanner;
/**
*
* #author taine
*/
public class AvarageCalc {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
Scanner input = new Scanner(System.in);
double num1;
double num2;
double num3;
double num4;
double num5;
double num6;
double num7;
double num8;
double num9;
double num10;
double ans;
System.out.print("Enter Number #1:");
num1 = input.nextDouble();
System.out.print("Enter Number #2:");
num2 = input.nextDouble();
System.out.print("Enter Number #3:");
num3 = input.nextDouble();
System.out.print("Enter Number #4:");
num4 = input.nextDouble();
System.out.print("Enter Number #5:");
num5 = input.nextDouble();
System.out.print("Enter Number #6:");
num6 = input.nextDouble();
System.out.print("Enter Number #7:");
num7 = input.nextDouble();
System.out.print("Enter Number #8:");
num8 = input.nextDouble();
System.out.print("Enter Number #9:");
num9 = input.nextDouble();
ans = num1 + num2 + num3 + num4 + num5 + num6 + num8 + num9;
System.out.println("The Average of the numbers you gave is:" + ans / 9);
}
}
When the program runs:
run:
Enter Number #1:20
Enter Number #2:20
Enter Number #3:20
Enter Number #4:20
Enter Number #5:20
Enter Number #6:20
Enter Number #7:20
Enter Number #8:20
Enter Number #9:20
The Average of the numbers you gave is:17.77777777777778
BUILD SUCCESSFUL (total time: 10 seconds)
Your average is incorrect because you are missing num7 in your sum
ans = num1 + num2 + num3 + num4 + num5 + num6 + num8 + num9;
should be
ans = num1 + num2 + num3 + num4 + num5 + num6 + num7 + num8 + num9;
You have 10 variables, but you calculate average of 9. Is it what you want? Anyway, #the-tom has showed your mistake. You've forgot about num7 variable.
The less lines of code you have the less possibility to get an error.
Probably will be better to do something like that:
double ans = 0;
Scanner input = new Scanner(System.in);
int x = 9 //Or some other number
for(int i = 1; i <= x; i++){
System.out.print("Enter Number #" + i);
ans += input.nextDouble();
}
System.out.println("The Average of the numbers you gave is:" + ans / x);
Now if you need to calculate average of 20 elements, all you need is just set the value of x to 20.

quadratic formula with scanner inputs

Okay so I am a complete Java noob, and I'm trying to create a program for class that runs a quadratic equation using scanner inputs. So far what I've got is this:
import java.util.*;
public class QuadraticFormulaSCN {
public static void main(String[]args) {
System.out.println("insert value for a:");
Scanner scan1 = new Scanner(System.in);
double a = scan1.nextDouble();
System.out.println("insert value for b:");
Scanner scan2 = new Scanner(System.in);
double b = scan2.nextDouble();
System.out.println("insert value for C:");
Scanner scan3 = new Scanner(System.in);
double c = scan3.nextDouble();
double answer =((Math.sqrt(Math.pow(b,2)-(4*a*c))-b)/2);
double final2 =(-b + Math.sqrt(Math.pow(b,2)-(4*a*c)))/2;
System.out.println("The x values are:" + answer + final2);
}
}
But I get a weird output, specifically NaNaN... What do I do to fix this? What am I doing wrong?
I'm a little late to answer, but I corrected your problems (described in the other answers), fixed one of your calculations, and cleaned up your code.
import java.util.*;
public class Test {
public static void main(String[] args)
{
Scanner s = new Scanner(System.in);
System.out.println("Insert value for a: ");
double a = Double.parseDouble(s.nextLine());
System.out.println("Insert value for b: ");
double b = Double.parseDouble(s.nextLine());
System.out.println("Insert value for c: ");
double c = Double.parseDouble(s.nextLine());
s.close();
double answer1 = (-b + Math.sqrt(Math.pow(b, 2) - (4 * a * c))) / (2 * a);
double answer2 = (-b - Math.sqrt(Math.pow(b, 2) - (4 * a * c))) / (2 * a);
if (Double.isNaN(answer1) || Double.isNaN(answer2))
{
System.out.println("Answer contains imaginary numbers");
} else System.out.println("The values are: " + answer1 + ", " + answer2);
}
}
NaN is something you get when the calculation is invalid. Such as dividing by 0 or taking the squareroot of -1.
When I test your code with a = 1, b = 0 and c = -4 the answers is 2.02.0
The formatting is not right and the calculation of final2 is not negated.
Otherwise the code is right.
To improve you could check whether the discriminant is negative.
double d = b*b -4 * a * c;
if (d < 0){
System.out.println("Discriminant < 0, no real solutions" );
return;
}
double x1 = (-b -sqrt(d))/(2*a);
double x2 = (-b +sqrt(d))/(2*a);
System.out.format("The roots of your quadratic formula are %5.3f and %5.3f\n",x1,x2);
Or, if you prefer support for solutions from the complex domain:
if (d < 0) {
System.out.println("Discriminant < 0, only imaginary solutions");
double r = -b / (2 * a);
double i1 = -sqrt(-d) / (2 / a);
double i2 = sqrt(-d) / (2 / a);
System.out.format("The roots of your quadratic formula are (%5.3f + %5.3fi) and (%5.3f + %5.3fi)\n",r, i1, r, i2);
return;
}
You are getting NaN because you are attempting to take the square root of a negative number. In math that's not allowed unless you are allowing complex numbers, e.g. 1 +/- 2i.
This can happen in quadratic formulas when the discriminant (the thing in the square root) is negative, e.g. x^2 + 6*x + 100: b^2 - 4ac = 36 - 400 = -364. Taking the square root of a negative number in Java leads to NaN. (not a number)
To test for NaN, use Double.isNaN and handle the NaN appropriately.
In addition, your calculations are incorrect even if NaN isn't being encountered:
$ java QuadraticFormulaSCN
insert value for a:
1
insert value for b:
5
insert value for C:
6
The x values are:-2.0-2.0
This should have outputted 2.0 and 3.0
You should only do the calculation when
discriminant is equal or greater than zero
if(((Math.pow(b,2)-(4*a*c))>= 0){ /* Calculation here */ }
else {/*error message or complex number calculus*/};
One thing I always try to do is put all my math in appropriate parenthesis to avoid an, all too easy, Order of Operations mistake. The NaN is saying "Not a number." You would also get that message if the user input numbers that could not produce a result, such as a trying to get the square root of a negative number. Also, just as a note, you can save sometime by only using on Scanner for a,b, and c.
public class QuadraticFormula{
public static void main(String[] args){
java.util.Scanner input = new java.util.Scanner(System.in);
double a = input.nextDouble();
double b = input.nextDouble();
double c = input.nextDouble();
double quadPos = (-b + Math.sqrt(Math.pow(b,2)-(4*a*c)))/(2*a);
double quadNeg = (-b - Math.sqrt(Math.pow(b,2)-(4*a*c)))/(2*a);
System.out.println("-b - = " + quadNeg + "\n-b + = " + quadPos);
}
}

how to get two variables to print with one in decimal form

I am very new. apologies in advance for my coding. I need to print a table that shows year and then a tab over, and then the value with a next line. The value has to be in decimal form.
I have been reading and searching and mixing my code around. I have found it for 1 variable but not for two in same line. I have tried the printf, I have tried the good ol 100 / 100.0 and I either get errors or the decimal never goes to 2 places. I do not need it rounded, just with 2 spaces after. I am obviously going wrong somewhere. I would appreciate any assistance.
import java.util.Scanner;
public class Investment1 {
public static double futureInvestmentValue(double investmentAmount, double monthlyInterestRate, int years){
double principal = 0.0;
double futureInvestmentValue = 0;
for (years = 1; years <=30; years++){
//calculate futureInvestmentValue
futureInvestmentValue = (investmentAmount * (Math.pow (1 + monthlyInterestRate, years * 12)));
System.out.print(years + "\t" + futureInvestmentValue + "\n");
}//end for
return futureInvestmentValue;
}//end futureInvestmentValue
public static void main(String[] args){
Scanner input = new Scanner (System.in);
//obtain Investment amount
System.out.print("Enter Investment amount: ");
double investmentAmount = input.nextDouble();
//obtain monthly interest rate in percentage
System.out.print("Enter annual interest rate in percentage: ");
double annualInterestRate = input.nextDouble();
double monthlyInterestRate = (annualInterestRate / 1200);
int years = 30;
System.out.println("Years\t" + "Future Value");
System.out.print(years + "\t");
System.out.print(years + "\t" + ((int)(futureInvestmentValue(investmentAmount, monthlyInterestRate, years))) + "\n");
}//end main
}//end Investment
You can use system.out.format():
System.out.format("%d \t %.2f", years, futureInvestmentValue);
you should read about format strings, heres a simple usage example:
System.out.println(String.format("%d %.2f",myint,myfloat));
myint will be printed as an integer (even if it's a floating point value) due to the use of the %d in the format string.
myfloat will be printed as a decimal number with 2 digits after the decimal point, thanks to the %f.2 part in the format string.

Categories