Java: how do I initialize an array size if it's unknown?

前端 未结 7 637
庸人自扰
庸人自扰 2021-02-04 03:47

I\'m asking the user to enter some numbers between 1 and 100 and assign them into an array. The array size is not initialized since it is dependent on the number of times the us

7条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-02-04 04:00

    If you want to stick to an array then this way you can make use. But its not good as compared to List and not recommended. However it will solve your problem.

    import java.util.Scanner;
    
    public class ArrayModify {
    
        public static void main(String[] args) {
            int[] list;
            String st;
            String[] stNew;
            Scanner scan = new Scanner(System.in);
            System.out.println("Enter Numbers: "); // If user enters 5 6 7 8 9 
            st = scan.nextLine();
            stNew = st.split("\\s+");
            list = new int[stNew.length]; // Sets array size to 5
    
            for (int i = 0; i < stNew.length; i++){
                list[i] =  Integer.parseInt(stNew[i]);
                System.out.println("You Enterred: " + list[i]);
            }
        }
    }
    

提交回复
热议问题