Java中如何輸入一個數組


第一種方法:(不限制輸入數組的長度)

  System.out.println("請輸入幾個數並用逗號隔開:");
  Scanner sc = new Scanner(System.in);
  String str = sc.next().toString();
  String[] arr  = str.split(",");
  int[] b = new int[arr.length];
  for(int j = 0; j<b.length;j++) {
   b[j] = Integer.parseInt(arr[j]);
   System.out.println(b[j]+" ");
  }

第二種方法:(限制輸入的個數)

System.out.println("請輸入三個數:");
Scanner in = new Scanner(System.in);
int[] b=new int[3];
for(int i=0;i<b.length;i++){
b[i]=in.nextInt();
}

 

————————————————
版權聲明:本文為CSDN博主「Baby~卓」的原創文章,遵循CC 4.0 BY-SA版權協議,轉載請附上原文出處鏈接及本聲明。
原文鏈接:https://blog.csdn.net/weixin_43157131/article/details/88126490

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM