更新時間:2022-08-17 08:25:18 來源:動力節(jié)點(diǎn) 瀏覽5609次
在Java中要怎么輸入數(shù)字?動力節(jié)點(diǎn)小編來告訴大家。
java的Scanner類提供了nextInt、nexFloat、nextDouble等方法,可以像類似C語言的scanf那樣讀取指定類型的數(shù)字。
首先定義一個Scanner對象:Scanner sn = new Scanner(System.in);
用sn.nextInt讀取整型數(shù),注意如果輸入的不是整形數(shù)則該函數(shù)會拋出InputMismatchException異常,應(yīng)予以捕獲。
System.out.print("請輸入一個整數(shù):");
try{
intVal = sn.nextInt();
System.out.println("你輸入了:" + intVal);
}
catch(InputMismatchException e){
System.out.println("必須輸入整數(shù)!");
}
用sn.nextFloat讀取單精度浮點(diǎn)數(shù),如果輸入的不是數(shù)字則也會拋出InputMismatchException異常,應(yīng)予以捕獲。System.out.print("請輸入一個浮點(diǎn)數(shù):");
try{
floatVal = sn.nextFloat();
System.out.println("你輸入了:" + floatVal);
}
catch(InputMismatchException e){
System.out.println("必須輸入數(shù)!");
}
用sn.nextDouble讀取雙精度浮點(diǎn)數(shù),操作與單精度類似。System.out.print("請輸入一個浮點(diǎn)數(shù):");
try{
doubleVal = sn.nextDouble();
System.out.println("你輸入了:" + doubleVal);
}catch(InputMismatchException e)
{
System.out.println("必須輸入數(shù)!");
}
流使用完畢后應(yīng)予以關(guān)閉:sn.close();
相關(guān)閱讀
初級 202925
初級 203221
初級 202629
初級 203743