Java中從鍵盤輸入多個整數
阿新 • • 發佈:2019-01-10
例題:求數列的和
分別輸入兩個整數n,m,中間以空格隔斷,n 為數列第一項,後面各項均為前一項的開根號,求前m項的和。
第一種從鍵盤輸入並讀取的方式:sc.hasNextInt() 函式和sc.nextInt()函式
hasNextInt() 判斷當前輸入的是否是整數
import java.util.Scanner; import java.lang.Math.*; class Test1{ public static void main(String [] args){ Scanner sc=new Scanner(System.in); int m; double n,result; while(sc.hasNextInt()){ n=sc.nextInt(); m=sc.nextInt(); result=0; for(int i=0; i<m; i++){ result += n; n = Math.sqrt(n); } System.out.printf("%.2f",result); } } }
第二種方式:sc.trim()函式 和sc.split()函式
sc.trim() 去掉字串首尾空格
sc.split() 按照指定字元(串)或正則去分割某個字串 ,結果以字串陣列形式返回
import java.util.Scanner; import java.lang.Math.*; class Test{ public static void main(){ Scanner sc=new Scanner(System.in); String input=sc.nextLine(); input=input.trim();//去掉字串首尾空格 String[] temp=input.spilt(" "); //按照指定字串分割某個字串並以字串陣列形式返回 double n=Integer.parseDouble(temp[0]); int m=Integer.parseInt(temp[1]); double result=0; for(int i=0; i<m; i++){ result += n; n = Math.sqrt(n); } System.out.println(result); } }