String can not be converted to double - wrong JOptionPane for input? - java

I keep getting the error "String can not be converted to double" I have tried re-defining my variables as int but that doesn't seem to work — I just get a flag saying that loss will occur converting double to int. Im curious as to wether or not I'm using the wrong JOptionPane when calling for input from the user or if my variable declarations are wrong.
Any help would be greatly appreciated.
package pf_javaass01c;
import javax.swing.JOptionPane;
public class ConversionCalculator
{
final static String HEADING = "Conversion Calculator";
final static double CONVERSION = 0.6214;
final static double PI = 3.14159;
public static void main(String[] args)
{
// Input Variables
double kilometers, convertedKilometers, miles, convertedMiles;
double width, length, areaRectangle, perimeterRectangle;
double radius, circumference, areaCircle;
// Kilometer to Miles Calculator
kilometers = JOptionPane.showInputDialog(null, "Please enter a kilometer value you wish to convert to miles;", HEADING, JOptionPane.QUESTION_MESSAGE);
convertedKilometers = kilometers * CONVERSION;
JOptionPane.showMessageDialog(null, kilometers + " kilometers is equal to " + convertedKilometers + " miles.", HEADING, JOptionPane.INFORMATION_MESSAGE);
} // End of main
} // End of ConversionCalculator

The value returned by the JOptionPane is a String. You are trying to put that value into kilometers, which is a double. You're basically trying to fit a sphere into a triangular hole. As a result, the error occurs.
The solution is to simply parse, or convert, the string to a double. To do that, call Double.parseDouble():
// get the user input and put it into a string variable first
String userInput = JOptionPane.showInputDialog(null, "Please enter a kilometer value you wish to convert to miles;", HEADING, JOptionPane.QUESTION_MESSAGE);
// parse the user's input and assign the result to kilometers
kilometers = Double.parseDouble(userInput);

Double.parseDouble() was the answer with new variables that allow for user input to be converted to double!

Related

Number Format Exception?

if (input.equals("arbitrary"))
{
System.out.println("What is your mass?");
massPerson = Double.parseDouble(input);
System.out.println("What is the planet's weight?");
massPlanet = Double.parseDouble(input);
System.out.println("What is the radius of the planet?");
radiusPlanet = Double.parseDouble(input);
weight = arbitraryPlanetWeight(massPerson, massPlanet, radiusPlanet);
}
I'm trying to run a program where it returns your weight on different planets. Everything is working except for my arbitrary planet. if you type "arbitrary" in the void main(string[]args) it asks "What is your weight" and stops running the args. It says i have a NumberFormatException. How can I fix this?
I have written you a example of what I assume you are trying to do.
Read all the comments and they should help you understand the code.
public static void main(String[] args) {
/*args is a array of String so for example:
["arbitrary"] -> array of length == 1
or
["12.2","11.1","13.3"]
*/
//If there were no elements in the array this code would break but we will assume there is at least one
String input = args[0];//put the first element in the array into input
double weight,massPerson,massPlanet,radiusPlanet;//define variables that we will use
if (input.equals("arbitrary"))//we look is the string equal to "arbitrary"
{
System.out.println("What is your mass?");
//The next commented out line if it where a command could not pass here because you are trying to interpret "arbitrary" as a double value
//double massPerson = Double.parseDouble(input);
//instead you want to user to input the value
Scanner s = new Scanner(System.in);
input = s.nextLine(); //now input is what the user has entered
//we assume that what the user has entered is a number
//if the user input something like "hello" the code would break and you would again get the NumberFormatException
massPerson = Double.parseDouble(input);
System.out.println("What is the planet's weight?");
input = s.nextLine();
massPlanet = Double.parseDouble(input);
System.out.println("What is the radius of the planet?");
input = s.nextLine();
radiusPlanet = Double.parseDouble(input);
s.close();//it is important to close the scanner -> there is also a try syntax to do this closing automatically so google : " try-with-resources Statement"
}
else{//we have something else as the input
//lets assume then that the args[] has 3 values which can all be parsed
//also since we have the values there is no need to ask the user
massPerson = Double.parseDouble(args[0]);//take the first value in the args array and pars it
massPlanet = Double.parseDouble(args[1]);//take the second value in the args array and pars it
radiusPlanet = Double.parseDouble(args[2]);//take the third value in the args array and pars it
}
//we have all the values at this point so we can calculate the weight
weight = arbitraryPlanetWeight(massPerson, massPlanet, radiusPlanet);
}
private static double arbitraryPlanetWeight(double massPerson, double massPlanet, double radiusPlanet) {
System.out.println("Do some calculations");
return 50;//dummy result
}
If your String input is equal to arbitrary, It can't be the representation of a number, then the Double.parseDouble(input) launches a parse exception.
You should have variables for each information you want:
if (input.equals("arbitrary"))
{
System.out.println("What is your mass?");
massPerson = Double.parseDouble(massPersonStr);
System.out.println("What is the planet's weight?");
massPlanet = Double.parseDouble(massPlanetStr);
System.out.println("What is the radius of the planet?");
radiusPlanet = Double.parseDouble(radiusPlanetStr);
weight = arbitraryPlanetWeight(massPerson, massPlanet, radiusPlanet);
}

How to multiply a set number and a user input number in Java?

I want to make a calculator that greets the user by name then multiplies one number that the user enters and one number that I set. For instance, if the user enters the number 10, I want my code to take the 10 and multiply it by 6.
Here's what I have so far:
import java.util.Scanner;
public class Calculator {
public static void main(String[] args){
Scanner userInputScanner = new Scanner(System.in);
System.out.println ("Hello, my name is Bob. What is your name?");
String userName = userInputScanner.nextLine();
System.out.println ("Hello" + userName + "how many steps do you take in a ten second interval?");
}
}
This part is working, but I can't figure out what to do next.
If you take a look at the Javadoc for Scanner, there is a nextInt() method, which will do the same thing as nextLine() but return an integer. You can set that to an integer variable.
To multiply two variables, it's as simple as
int z = x * y;
Then print out the result, or to simplify it, you could just print out the calculation without setting it equal to a variable
System.out.println("The awnser is: " + (scanner.nextInt() * 6));
Keep in mind, this are integers, you could also use doubles or floats, or even longs. See the scanner documentation for all the methods you can use to get input.
Use nextInt() (or nextDouble() or ...) method to read the number the user will input.
int userNumber = (userInputScanner.hasNext()) ? userInputScanner.nextInt() : 0;
System.out.println("6 * " + userNumber + " = " + (6 * userNumber));

Having trouble with calculations... what's wrong?

Having trouble calculating this out. The rest of the coding is fine but this one class. The error focuses on one line.
retail_price = double.parseDouble(input1) * (double.parseDouble(input2) / 100);
The errors tell me that "class expected" "; expected" and "not a statement". Where am I going wrong because this seems correct to me?
private class CalcButtonListener implements ActionListener
{
// The actionPerformed method executes when the user clicks the calculate button
public void actionPerformed(ActionEvent e)
{
double retail_price;
String input1;
String input2;
//Get the number from the users input in priceFeild1
input1 = priceField1.getText();
//Get the number from the users input in priceFeild2
input2 = priceField2.getText();
// Calculate out the operation below to find the retail_price
retail_price = double.parseDouble(input1) * (double.parseDouble(input2) / 100);
JOptionPane.showMessageDialog(null, "The retail price of the item is: $" + retail_price );
}
The name of the class containing parseDouble is Double, not double. They are not synonyms. double is the name of the primitive type, and primitives do not have methods.
So you need:
retail_price = Double.parseDouble(input1) * (Double.parseDouble(input2) / 100);
However, you should also strongly consider using BigDecimal instead of Double anyway, as that's a better match for currency values.
Additionally, I'd recommend:
Following Java naming conventions, using camelCase instead of underscore separators
Giving your variables more meaningful names - what are input1 and input2 meant to represent? A price and a discount, perhaps?
Declaring variables only where you need to, rather than at the start of the method
Considering what you want to happen if the value entered by the user isn't a valid number
Considering whether you care about internationalization (e.g. a user entering "10,50" instead of "10.50". If so, look at NumberFormat and DecimalFormat
Try:
Double.parseDouble(input1)
parsing of double retail_price = Double.parseDouble(input1) * (Double.parseDouble(input2) / 100);

NumberFormatException when parsing String to Float value [duplicate]

This question already has answers here:
How to do an Integer.parseInt() for a decimal number?
(10 answers)
Closed 4 years ago.
System.out.println("Enter a number: ");
String in1 = input.nextLine();
Integer input1 = Integer.valueOf(in1);
Float input2 = Float.parseFloat(in1);
Double input3 = Double.valueOf(in1).doubleValue();
System.out.println();
System.out.println("Enter another number: ");
String in2 = input.nextLine();
Integer input21 = Integer.valueOf(in2);
Float input22 = Float.parseFloat(in2);
Double input23 = Double.valueOf(in2).doubleValue();
FloatN fco = new FloatN();
System.out.println();
System.out.println("The sum of both of your numbers is: " + fco.add(input2, input22));
done = true;
I'm well aware that this program is completely impractical, I only wrote it to practice parsing, generics, and interfaces. I tried Integer, which worked fine, but upon trying the Float and Double.add() functions, I get 3 errors:
at java.lang.NumberFormatException.forInputString
at java.lang.Integer.parseInt
at java.lang.Integer.valueOf
I removed the Integer parsers, and the program worked fine. I'm confused as to why I get the errors only when I enter Decimal values and would like someone to help point out what exactly is causing the exception so I can avoid any errors like this in the future, and since removing the Integer parser removes any functionality from the IntegerN class.
Also, if anyone needs the FloatN class for whatever reason:
public static class FloatN implements Summization<Float>{
public FloatN(){}
public Float add(Float a, Float b)
{
return a + b;
}
}
Summization is a generic interface with an add() method.
Thanks in advance.
If you enter a decimal value as input, Integer.parseInt() method won't be able to parse it. If you still want to have them all in your code, you have to get int value of that Float value. You can use intValue() method:
Float input2 = Float.parseFloat(in1);
Integer input1 = Integer.valueOf(input2.intValue());
Maybe add string which is not contain a parsable float or it is null.
From javadoc:
NullPointerException - if the string is null
NumberFormatException - if the string does not contain a parsable float.
becuase Integer.valueOf(in2); this line will give NumberFormatException with float and double you can use
Number num = NumberFormat.getInstance().parse(myNumber);
see # http://docs.oracle.com/javase/7/docs/api/java/text/NumberFormat.html
The NumberFormatException comes in the Integer parser, and not in the Double and Float parsers if input contains decimal.
In such situations, you can get the the integer part of the decimal number using split and parse:
String[] s = in1.split("\\.");
Integer input1 = Integer.valueOf(s[0]);
Float input2 = Float.parseFloat(in1);
Double input3 = Double.valueOf(in1).doubleValue();

Making the output of an operation to display 2 decimal points

Here's my current code:
import java.util.Scanner;
public class Addition
{
// main method begins execution of Java application
public static void main( String args[] )
{
// create Scanner to obtain input from command window
Scanner input = new Scanner( System.in );
int area;
int number1;
int number2;
System.out.print( "Input base value = " ); // prompt
number1 = input.nextInt(); // read first number from user
System.out.print( "Input height value = " ); // prompt
number2 = input.nextInt(); // read second number from user
area = 1/2*(number1*number2); // add numbers
System.out.printf( "The Area of the right triangle is %d\n", area ); // display sum
} // end method main
} // end class Addition
I would like to make it display the decimal point when i input 5 as the first and second number. i tried replacing int area with double area but doesn't work..
If you want two digits after the decimal point, you must make area a double and use a format string of %1.2f.
Example:
System.out.printf("%1.2f\n", 78785.7);
You can check out the vast array of examples here:
Formatting Numerical Data
Hope it helps :) Cheers!
In addition to making area a double, you'll also need to make at least one of the terms in 1/2*(number1*number2) a double, or you'll only be doing int math, which won't turn out how you expect. For example:
1.0/2*(number1*number2)
In your output, you'll also have to use %f instead of %d.

Categories