I get inputs from user and read it line by line.Then I'm using split method to tokenize the inputs. Like this:
Scanner input=new Scanner(System.in);
String input1=input.nextLine();
String[] tokens=input1.split(" ");
method1(Double.parseDouble(tokens[0]),Double.parseDouble(tokens[1]));
Here is method1
:
public static void method1 (double a, double b) {
System.out.println(a);
System.out.println(b);
}
When I declare 3.5 and 5.3 output;
3.5
5.3
Here there is no problem but if I declare 3,5 and 5,3 my code giving error in below;
Exception in thread "main" java.lang.NumberFormatException: For input string: "3,5"
at sun.misc.FloatingDecimal.readJavaFormatString(Unknown Source)
at java.lang.Double.parseDouble(Unknown Source)
How can I fix this problem?
Using NumberFormat
you can do something like this:
NumberFormat f = NumberFormat.getInstance(Locale.FRANCE);
double myNumber = f.parse("3,5").doubleValue();
Now you can pass myNumber
to the method that accepts double
value.
When using Locale.FRANCE
, you tell Java that you write double
numbers with ,
instead of .
.
You could use DecimalFormat
like this:
DecimanFormat df = new DecimalFormat("#.#", DecimalFormatSymbols.getInstance());
Double returnValue = Double.valueOf(df.format(input1));
So DecimalFormatSymbols.getInstance()
will get the default locale and its correct symbols.
Read More about DecimalFormat
.
what i guess is : your input via scaner is
3.5 5.3
and you have applied
String[] tokens=input1.split(" ");
so it has divided your strings in to substrings ie 3.5 and 5.3 if you give your input as
3.5,5.3
It will be a success and it will compile without an error..
in your case
input 3,5 5,3
it you just need to put a "," in split method like :
String[] tokens=input1.split(",");
and it will work with output as ....
3
5 5
3
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.