1. 程式人生 > >Java控制檯接收使用者輸入

Java控制檯接收使用者輸入

Java控制檯接收使用者輸入

接收陣列

陣列長度未知

輸入用例:2,3,4,5,1
public static void main(String[] args) {
           Scanner in = new Scanner(System.in);
           while (in.hasNext()){
               String s = in.nextLine();

               String[] str = s.split(","); //按照逗號分隔
               int[] a = new int[str.length];
               for (int i = 0; i < str.length; i++) {
                   a[i] = Integer.parseInt(str[i]);
                   System.out.println(a[i]);
               }
           }
       }

陣列長度已知

輸入用例:
5
2,3,4,5,1
 public static void main(String[] args) {
            Scanner input = new Scanner(System.in);
            int arrLength;
            arrLength = input.nextInt();
            String a = input.nextLine();
            String[] array = input.nextLine().split(",");//按照逗號分隔
            int[] arr = new int[arrLength];
            int[] arrDup = new int[arrLength];
            for (int i = 0; i < arrLength; i++) {
                arr[i] = Integer.parseInt(array[i].trim());
                System.out.println(arr[i]);
            }
        }