輸入不確定長度的數組
import java.util.*;
public static void main(String[] args){
System.out.println("請輸入一串整數,並用空格隔開,以回車結束");
Scanner sc = new Scanner(System.in);
String[] str = sc.nextLine().split(" ");
int num[]=new int[str.length];
for(int i=0;i<num.length;i++){
num[i]=Integer.parseInt(nums[i]);
}
System.out.println("輸入的數組為:"+Arrays.toString(a));
}
參考大神寫法
//一組無序的自然數集合,由0,1,2... ...,n的數字和一個的數字X(X>=0 && X<=n)組成,請從集合中找出這個重復數字X。
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashSet;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String[] numstr=br.readLine().split(" ");
int length=0;//記錄集合元素數
HashSet<String> hs=new HashSet<>();
for(int i=0;i<numstr.length;i++)
{
length=hs.size();
hs.add(numstr[i]);
if(length==hs.size()){//沒存入
System.out.println(numstr[i]);
break;
}
}
}
}
自定義數組的長度
//一組無序的自然數集合,由0,1,2... ...,n的數字和一個的數字X(X>=0 && X<=n)組成,請從集合中找出這個重復數字X。
import java.util.*;
public class ArrayIO{
public static void main(String[] args){
int ARRAYLENGTH = 8; //指定數組長度
int a[] = new int[ARRAYLENGTH];
Scanner sc = new Scanner(System.in);
System.out.println("請輸入數組,並以回車結束:");
for(int i = 0; i < a.length; i++){
a[i] = sc.nextInt();
}
//直接打印數組a出來的是數組的首地址,必須用toString方法
System.out.println("數組a為:" + Arrays.toString(a));
}
}
輸出
請輸入數組,並以回車結束:
1 2 3 4 8 7 6 5
數組a為:[1, 2, 3, 4, 8, 7, 6, 5]