Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting 1000 as an answer instead of 1 when dividing (6.022/6.022=1000) Java

So, I'm new to programming, and I was trying to make a basic mole (chemistry) calculator just for fun. I didn't find this question. If it was answered please send me the link.

This is the formula: n = N / Na where n = mole and Na = 6.022E23

The first part of the code throws an error. Just trying to get one, dividing Na by my given N, and even with 6.022 instead of 6.022E23 I'm getting 1000.0 as an answer.

Scanner in = new Scanner(System.in);
double Na = 6.022;

System.out.print("What do you want to know? Mol(0) or N(1)? ");
int first = in.nextInt();
if (first == 0){
    System.out.print("Insert N: ");
    double N = in.nextDouble();
    double mol = N/Na;
    System.out.print("There are " + mol + " mol in that sample.");
}
else if (first == 1){
    System.out.print("Insert mol: ");
    double mol = in.nextDouble();
    double N = mol*Na;
    System.out.print("There are " + N + " molecules, atoms or ions in that sample.");   
}

Output 0:

What do you want to know? Mol(0) or N(1)? 0  
Insert N: 6.022  
There are 1000.0 mol in that sample.  

Output 1:

What do you want to know? Mol(0) or N(1)? 1  
Insert mol: 1  
There are 6.022 molecules, atoms or ions in that sample.  

Thanks in advance.

like image 946
EnderEgg Avatar asked Feb 22 '14 10:02

EnderEgg


1 Answers

Since you are writing a small code, the simplistic suggestion to a new coder I could make is hard code it so it is:

double mol = N/6.022;

this gives you what you want. The error is because it is seeing it as 6022 instead of 6.022 since it is recognizing the . as a thousands indicator. Hope this helps.

If you do not want to hardcode the value, add:

in.useLocale(Locale.US);

right below where you declare your scanner. Both of these solutions should fix your problem.

like image 77
Lain Avatar answered Sep 30 '22 05:09

Lain