简体   繁体   中英

need scanner input for array

does anyone know how to set a user input for an array, I cant find the command anywhere. my array 'grades' have 20 locations. im not so sure about 'grades.length' function but I think it prompts 20 times. BUT I added a while statement to override BUT ITS TOTALLY IGNORING THE FOR STATEMENT. if I could set user input for array I could get rid of the while statement... program has to accept grade for number of students the user inputs btw..

import java.util.Scanner;

public class gradesaverage {

    public static void main(String[] args) {
        int [] grades = new int [20];
        int i;
        int numStudents;

        System.out.print("Enter number of students: ");
        Scanner scanint = new Scanner (System.in);      
        numStudents = scanint.nextInt();        

        for ( i = 1;  i <= grades.length; ++i)
        {
            System.out.println("Enter grade: ");
            grades[i] = scanint.nextInt();
        }
        while(i <= numStudents );

    }

}

Not sure what you mean, but assuming all input is correct,

int [] grades = new int [numStudents ];

Should work if you move this line after declaration and assignment of numStudents . There is no problem in java with variable length arrays.

Also note - your iterator i starts from 1, while in java arrays start from 0.

public static void main(String[] args) {
    int i;
    int numStudents;
    System.out.print("Enter number of students: ");
    Scanner scanint = new Scanner (System.in);      
    numStudents = scanint.nextInt();
    int [] grades = new int [numStudents]; //the size we wanted
    for ( i = 0;  i < grades.length; ++i) //starting from 0, not 1.
    {
        System.out.println("Enter grade: ");
        grades[i] = scanint.nextInt();
    }
    //print the array - for checking out everyting is ok
    System.out.println(Arrays.toString(grades)); 
}

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