我已经编写了这段代码,但是,每次我输入一个十进制值时,它都不起作用。即使输入十进制值,如何使此代码正常工作?例如,如果我输入值7.5,则应显示“运费为$ 9.45”
import java.util.Scanner;
public class IfElse {
public static void main(String[] args) {
int marksObtained;
Scanner input = new Scanner(System.in);
System.out.println("Please enter a package weight in pounds:");
marksObtained = input.nextInt();
if (marksObtained>20)
{
System.out.println("The package is too heavy to be shipped");
}
else if (marksObtained>10)
{
System.out.println("The shipping cost is $12.50");
}
else if (marksObtained>3)
{
System.out.println("The shipping cost is $9.45");
}
else if (marksObtained>1)
{
System.out.println("The shipping cost is $4.95");
}
else if (marksObtained>0)
{
System.out.println("The shipping cost is $2.95");
}
else if (marksObtained<0)
{
System.out.println("The weight must be greater than zero");
}
}
}
答案 0 :(得分:1)
您可以使用1 + 2 = 3
2 + 2 = 4
3 + 0 = 3
4 + 2 = 6
或nextFloat
nextDouble
使用Scanner s = new Scanner (System.in);
float a = s.nextFloat ();
System.out.println(a);
将期望输入一个int值,如果未输入nextInt
,则会抛出一个java.util.InputMismatchException
答案 1 :(得分:1)
查看用于读取输入的代码:
int marksObtained;`enter code here`
marksObtained = input.nextInt();
这里的关键是要了解int
只能代表整数值,不能代表小数。对于小数,您需要使用双精度或浮点型。例如:
double marksObtained = input.nextDouble();
我建议您回顾一下Java支持的基本数据类型。您还应该熟悉the documentation for the Scanner class以及标准Java API的其余文档。
答案 2 :(得分:1)
nextInt()
仅适用于整数。使用nextDouble()
答案 3 :(得分:1)
使用如下的nextDouble
方法
public static void main(String[] args) {
double marksObtained;
System.out.println("Please enter a package weight in pounds:");
Scanner input = new Scanner(System.in);
marksObtained = input.nextDouble();
input.close();
if (marksObtained > 20) {
System.out.println("The package is too heavy to be shipped");
} else if (marksObtained > 10) {
System.out.println("The shipping cost is $12.50");
} else if (marksObtained > 3) {
System.out.println("The shipping cost is $9.45");
} else if (marksObtained > 1) {
System.out.println("The shipping cost is $4.95");
} else if (marksObtained > 0) {
System.out.println("The shipping cost is $2.95");
} else if (marksObtained < 0) {
System.out.println("The weight must be greater than zero");
}
}
然后关闭扫描仪,这是个好习惯。