簡體   English   中英

如何使小數輸入有效?

[英]How can you make a decimal input valid?

我已經編寫了這段代碼,但是,每當我輸入一個十進制值時,它都不起作用。 即使輸入十進制值,如何使此代碼正常工作? 例如,如果我輸入值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");
        }
  }
}

您可以使用nextFloatnextDouble

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

使用nextInt將期望輸入一個int值,如果未輸入一個int則將拋出java.util.InputMismatchException

查看用於讀取輸入的代碼:

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

這里的關鍵是要理解一個int只能代表整數值,不能代表小數。 對於小數,您需要使用雙精度或浮點型。 例如:

double marksObtained = input.nextDouble();

我建議您返回並回顧Java支持的基本數據類型。 您還應該熟悉Scanner類的文檔以及標准Java API的其余文檔。

nextInt()僅適用於整數。 使用nextDouble()

使用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");
    }
}

關閉掃描儀,這是個好習慣。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM