I wrote this code: For each line, it should take the weighted average of these numbers with weights 0.2, 0.4, and 0.4, and it should print out the averaged value on a seperate line on the standard output. For example, for the input below
45.00 67.00 98.00
89.00 23.00 89.00
it should produce
75.00
62.60
It works when i write, for example 45,6 but it doesn't when i write 45.6. This is my code:
import java.util.Scanner;
public class paket {
public static void main (String [] args){
Scanner input=new Scanner(System.in);
float num1,num2,num3,result;
while(input.hasNext()){
num1=input.nextFloat();
num2=input.nextFloat();
num3=input.nextFloat();
result= (float) (num1*0.2+num2*0.4+num3*0.4);
System.out.println("Result is " +result);
}
}
}
在解析数字之前更改您的语言环境:
Locale.setDefault(new Locale("en", "US"));
A Scanner relies on a Locale to decide how to interpret its input. As other comments have noted, you're running on a system that assumes ',' is the decimal-point, rather than '.'
You can change the Locale your 'input' Scanner uses with
input.useLocale(Locale.US);
to have it interpret floats as using '.' for the decimal point.
You can set it back to your system's default with
input.reset();
You should use the locale when parsing, this way you support both . and , depending on what the user have chosen:
NumberFormat format = NumberFormat.getInstance(Locale.getDefault());
Number number = format.parse("1,234");
double d = number.doubleValue();
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.