简体   繁体   中英

How do I enter values from a loop into an array list?

this is my code:

public static void main(String[] args) {
    System.out.println("Please enter the number of values you would like to enter: ");
    Scanner scan = new Scanner(System.in);
    int intNumberOfNumbers = scan.nextInt();

    for (int i = 0; i < intNumberOfNumbers; i++) {
        System.out.println("Please enter a value for index " + i + ":");
        int intValue = scan.nextInt();
    }
}

What I'm trying to do is create a scanner that asks how many values they want to enter and whatever that value is, that's how many times it asks for number input. The problem is after I ask the question how can I add the number to an array list?

public static void main(String args[]){
   Scanner sc=new Scanner(System.in);
   int numOfInput=sc.nextInt();
   ArrayList<Integer> array=new ArrayList<Integer>();

   while(numOfInput-->0){
      array.add(sc.nextInt());       
   }
}
public static void main(String[] args) {
    System.out.println("Please enter the number of values you would like to enter: ");
    Scanner scan = new Scanner(System.in);
    int intNumberOfNumbers = scan.nextInt();
    ArrayList<Integer> myArray= new ArrayList<>();
    for (int i = 0; i < intNumberOfNumbers; i++) {
        System.out.println("Please enter a value for index " + i + ":");
        int intValue = scan.nextInt();
        myArray.add(intValue);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM