1

我已经编写了这段代码,但是,每次输入十进制值时,它都不起作用。即使输入十进制值,如何使此代码正常工作?例如,如果我输入一个值 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");
        }
  }
}
4

4 回答 4

1

您可以使用nextFloatnextDouble

Scanner s = new Scanner (System.in);
float a = s.nextFloat ();
System.out.println(a);

Using将期望输入一个 int 值,如果未输入anextInt将抛出 ajava.util.InputMismatchExceptionint

于 2019-02-05T01:37:07.870 回答
1

查看用于读取输入的代码:

int marksObtained;`enter code here`
marksObtained = input.nextInt();

这里的关键是要理解 anint只能表示整数值,不能表示小数。对于小数,您需要使用双精度或浮点数。例如:

double marksObtained = input.nextDouble();

我建议你回去复习一下 Java 支持的基本数据类型。您还应该熟悉Scanner 类的文档以及标准 Java API 的其余文档。

于 2019-02-05T01:37:24.800 回答
1

nextInt()仅适用于整数。利用nextDouble()

于 2019-02-05T01:38:41.700 回答
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");
    }
}

并关闭扫描仪,这是一个很好的做法。

于 2019-02-05T01:42:37.273 回答