Simple Double calculation in java (Centimeter square to meter square) - java

I was doing a simple calculation program in java when I encountered this problem. I want to convert centimeter square to meter square. 1 cm² = 0.0001 m². When i create the program in java to do this conversion I got result in '1.0E-4' instead of '0.0001'. I don't know why it is showing in that way. may someone guide me how to do it or something that may help
Here is the code:
import java.io.*;
class First {
public static void main(String x[]) {
try {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Please Enter the number");
double number = Double.parseDouble(br.readLine());
double d1 = 0.0001;
double result = number * d1;
System.out.println("Result is " + result);
} catch(Exception ex) {
ex.printStackTrace();
}
}
}

Doubles within a certain range are printed as a base and an exponent using the scientific notation.
1.0E-4 simply means 1 * 10^(-4), or 0.0001, so the answer you're getting is correct. As suggested by Smutje, you can change the way in which doubles are printed, like this.

Related

Syntax error on token "eqn" delete this token

I am fairly new to Java and taking a course but cannot figure out this small syntax error that I keep on getting. I have been researching and staring at the problem for a while now and just cannot figure it out. I am not asking for someone to complete the project just need help with this 1 error. Sorry if I am not posting in the right section. Below is the code....
import java.util.*;
public class SolveEqu {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
double arr[]=new double[3]; //passing array as parameter
System.out.println("Enter the three coefficients of the equation separated by spaces");
for(int i=0;i<3;i++)
arr[i]=sc.nextDouble();
double result[]=solveQuadratic(arr); // unknown
//if result is negative
if(result.length==1) {
System.out.println("The equation has no real roots");
}
//if result is = to zero
else if(result.length==2) {
System.out.println(" The equation has just one real root");
System.out.format("The root is %.2f",result[1]);
}
//if result is positive
else
{
System.out.println("The equation has two real roots");
System.out.format("The root are %.2f and %.2f",result[1],result[2]);
}
}
public static double[] solveQuadratic(double[] eqn) { // method heading from assignment
double discriminant=eqn[1]eqn[1]-(4eqn[0]eqn[2]); // discriminant of the quadratic equation
if(discriminant>0) { // discriminant is positive and has 2 real roots
double r1=(-eqn[1]+Math.sqrt(discriminant))/(2eqn[0]); // equation for square roots
double r2=(-eqn[1]-Math.sqrt(discriminant))/(2eqn[0]); //equation for square roots
double res[]= {2,r1,r2};
return res;
}
else if(discriminant==0) //equal to zero the equation has just one real root
{
double r1=(-eqn[1])/(2eqn[0]);
double res[]= {1,r1};
return res;
}
else // the equation has no real roots
{
double res[]= {0}; //unknown
return res; //unknown
}
}
}
The line that is causing me trouble and throwing errors on is the following ...
double discriminant=eqn[1]eqn[1]-(4eqn[0]eqn[2]);
It says "Invalid float literal number" and "Syntax error on taken "eqn", delete this token"
Could someone help explain what this error means?
The comment by #f1sh was the first of multiple examples of the same problem.
As pointed out, you needed a multiplication operator for eqn[1]*eqn[1].
For 4eqn[0]eqn[2], the same applies. If I remember my quadratics, you are trying to multiply there, so you need 4*eqn[0]*eqn[2]. The line should read:
double discriminant=eqn[1]*eqn[1]-(4*eqn[0]*eqn[2]);
Similarly, in your calculation for r1 and r2, 2eqn[0] should be 2*eqn[0]. That fix is needed in both places you calculate r1.
So, the basic rule is that, in java, you must specify the operator between two symbols. Unlike in math, writing them next to one another does not imply multiplication.

Comparing two values in Java

I have two values and I am trying to compare them, but getting the worng results:
public void subtotal() throws Exception {
WebDriverWait wait = new WebDriverWait(session.driver, 100);
double subtotal_price = 0;
DecimalFormat decimal = new DecimalFormat("0.00");
WebElement subtotal = wait.until(ExpectedConditions.visibilityOf( element("Subtotal_cart")));
Float subtotal_value = Float.parseFloat(subtotal.getText().substring(1));
logger.info("subtotal_value"+subtotal_value);
File file = new File("ItemUPC/ItemUPC.txt");
Scanner sc = new Scanner(file);
while (sc.hasNextLine()) {
String[] line = sc.nextLine().split("[|]");
String price = line[2];
subtotal_price = subtotal_price + Double.parseDouble(price);
}
logger.info("subtotal_price"+subtotal_price);
if ((subtotal_value)==(subtotal_price))
{
logger.info("Subtotals updated");
}
else
{
logger.info("Subtotals not updated");
}
}
The following is the ItemUPC file:
2|BATH BENCH|19.00
203|ORANGE BELL|1.78
When I print the value of subtotal_price and Subtotal_value I am getting both as 20.78, but when its getting compared in the if statement, I am getting output as "Subtotals not updated"
Not sure where I am getting wrong. Can someone please help? Thank you.
Comparing floating point numbers can be challenging, due to differences in precision between floating point types and their binary representations of decimal numbers.
You have two simple options:
Compare the absolute value of the difference between the two values to an epsilon, or threshold, value
Use BigDecimal as a substitute for your Float and double variable types
Example 1:
// simplification that may fail in certain edge cases
static final double EPSILON = .001; // acceptable error - adjust to suit your needs
if (Math.abs(subtotal_price - subtotal_value) < EPSILON) {
logger.info("Subtotals updated");
}
// ...
Example 2:
BigDecimal subtotal_price = new BigDecimal("0");
// ...
BigDecimal subtotal_value = new BigDecimal(subtotal.getText().substring(1));
// ...
if(subtotal_price.compareTo(subtotal_value) == 0) {
logger.info("Subtotals updated");
}
// ...

Input/Output - Arithmetic Equation

I am brand new to Java, started two weeks ago and am having issues wrapping my mind around this issue. I have a problem in a class I am taking that has been brought up before. Converting kilograms to pounds and rounding to the second decimal place.
I can create the input side of things and bring up a dialog box to prompt the user to enter in a weight. I can also create an output that uses an equation I made to output the answer in a dialog box.
My question is how do I take the information that is input and use it to convert from kilograms to pounds?
I have been reading my book and scouring the internet trying to find an answer and I think I may be over thinking it. Thanks for the help.
Input.java:
//This program asks a user to input a weight in kilograms.
package module2;
import javax.swing.*;
public class Input {
public static void main(String[] args) {
String weight;
weight = JOptionPane.showInputDialog("Enter weight in kilograms");
}
}
Output.java:
//This program outputs a converted weight from kilograms to pounds.
package module2;
import javax.swing.JOptionPane;
public class Output {
public static void main(String[] args) {
double kg = 75.5;
double lb = 2.2;
double sum;
sum = (kg * lb);
JOptionPane.showMessageDialog(null,sum, "Weight Conversion", JOptionPane.INFORMATION_MESSAGE);
}
}
Right now you have 2 main methods. Both of these are entry points for the program. Since they have to share information, it doesn't make sense you have both.
What I'd recommend is to change the Output's main method to a instance method, taking one parameter: the weight from the Input.
Like so:
public void printOutput(final double weight){
//...
}
You can then call that from the Input's main method like so:
public static void main(String[] args) {
String weight;
weight = JOptionPane.showInputDialog("Enter weight in kilograms");
double kg = Double.parseDouble(weight); // Be sure to parse the weight to a number
Output output = new Output(); // Create a new instance of the Output class
output.printOutput(kg); // Call our method to display the output of the conversion
}
One other thing, is that since Output is currently only used for that one method, you could consider just moving that method into Input.
// addition of two integers using JOptionPane
import javax.swing.JOptionPane;
public class Addition
{
public static void main(String[] args)
{
String firstNumber = JOptionPane.showInputDialog("Input <First Integer>");
String secondNumber = JOptionPane.showInputDialog("Input <Second Integer>");
int num1 = Integer.parseInt(firstNumber);
int num2 = Integer.parseInt(secondNumber);
int sum = num1 + num2;
JOptionPane.showMessageDialog(null, "Sum is" + sum, "Sumof two Integers", JOptionPane.PLAIN_MESSAGE);
}
}

Incrementing with a fraction based on user input

I'm having trouble i need to take a user input and increment it by 1/10 starting at 0 so if the user enters a 5.2 i need to to go through 0.1 0.2 0.3 etc display each and stop at 5.2 until the method is called again and a new input is entered here is what i have but it just runs through up until 10 i understand why it does this just not enough to be able to fix this any help would be appreciated
import java.util.Scanner;
public class SpeedChange {
public double startSpeed;
public double newSpeed;
public void changeUserSpeed(){
Scanner sc = new Scanner (System.in);
System.out.println("How fast would you like to go between 1-10 mph?");
double newSpeed = sc.nextDouble();
for(newSpeed = sc.nextDouble(); newSpeed <= 10.00; newSpeed+=.1 ){
System.out.println(newSpeed);
}
}
}
You need to change your loop content.Since your newSpeed has been specified by the user,you don't need to alter it.You simply need to create a new double variable,say Speed,which will increment in the limit of 0.1 at each iteration and keep running until your Speed equals newSpeed.
for(double Speed=0;Speed<=newSpeed;Speed+=0.1 ){
System.out.println(Speed); }
I hope this clears and solves your doubt!
Your code should instead be
for(double speed=0; speed <= newSpeed; speed+=.1 ){
System.out.println(speed);
}
P.S: double/float is not suitable for this kind of use. Use BigDecimal class to do this.
For details, see http://javarevisited.blogspot.in/2012/02/java-mistake-1-using-float-and-double.html?m=1

Refining an answer to x decimal places in java

I have an assignment and I need to get an input from the user to refine an answer to an x(the input of the user) number of decimal places. I'm going to refine my answer until there aren't any changes in the x decimal place.Can you please help on how I could achieve this answer?
It's not very clear what you are trying to achieve, but I think you want to accept a number and then round it up as the user specifies it.
Java's BigDecimal http://docs.oracle.com/javase/1.5.0/docs/api/java/math/BigDecimal.html class has all the functions you may need for this purpose. Please don't use the primary data types (float, double) as they will result in rounding errors sooner or later.
While it is true what #Thihara answers, maybe you need a bit simpler approach. Unless you need the precision of BigDecimal, you can do this:
int x = 4;
double value = 3.141593;
long answer = (long) (value * Math.pow(10, x));
The point is: multiply the value by 10^x and then convert to long (or int). Of course, this only works for small x.
There are a bunch of issues floating around here, that you should be aware of.
The first is that if you use a floating point number to represent your answer, you cannot represent every possible real number so you almost definitely will get rounding errors. Check out http://floating-point-gui.de/ for great information about this.
Secondly, when you print a float or double value, Java does some magic with it so that it looks nice. See Float.toString(float) and Double.toString(double) for more information.
So in reality, if you enter
double answer = 3.14159265;
it is stored as
3.141592650000000208621031561051495373249053955078125
which you can see using
System.out.println(new BigDecimal(answer));
So assuming you get your answer as a double (or float), you should use BigDecimal's setScale method. Also, if you want to limit the decimal places that your user can choose to the number visible when you print the double as a string, pass String.valueOf(answer) to BigDecimal's constructor.
Here is a little program that demonstrates how to do this
public static void main(String[] args) {
double answer = 3.14159265;
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String input = null;
do {
System.out.println("Answer: " + answer);
System.out.println("How many decimal places do you want? ");
try {
input = in.readLine();
} catch (IOException e) {
e.printStackTrace();
}
if (input != null) {
try {
int decimalPlaces = Integer.parseInt(input);
if (decimalPlaces < 0) {
System.out.println("Enter a positive value.");
} else {
BigDecimal scaled = new BigDecimal(
String.valueOf(answer));
if (decimalPlaces > scaled.scale()) {
System.out
.println("Answer does not have that many decimal places.");
} else {
scaled = scaled.setScale(decimalPlaces,
RoundingMode.HALF_EVEN);
System.out.println("Rounded answer: " + scaled);
}
}
} catch (Exception e) {
System.out.println("Not a valid number.");
}
}
} while (input != null);
}
Most of the code is error/input checking. The real work is done by setScale. Just keep in mind that there are many boundary conditions when working with floating point numbers, and you should be good!

Categories