-3
import java.util.Scanner;
public class Singleton{
    public static void main(String args[]){
        Scanner input = new Scanner(System.in);
        System.out.println("Enter number of students: ");
        int number = input.nextInt();
        String names[] = new String[number];
        for(int counter = 0; counter < 100; counter++){
            System.out.print("Enter name: ");
            names[counter] = input.nextLine();
            names[counter] = names[counter].toLowerCase();
        }
        int grades[] = new int[names.length];
        int count = 0;
        for(String x: names){
            System.out.print(x + "'s grade: ");
            grades[count] = input.nextInt();
            count++;
        }
        count = 0;
        for(String x: names){
            System.out.println(x + "'s grade is " + grades[count] + ".");
            count++;
        }
    }
}

can you help me to get something so I can put any number of values in the array without asking how many students there are?

Incognelo
  • 19
  • 4

3 Answers3

1

If you want an array that you can add a variable number of elements to you could use an ArrayList. i.e.

import java.util.ArrayList;

    ArrayList<String> names = new ArrayList<String>();
    for(int counter = 0; counter < 100; counter++){
        System.out.print("Enter name: ");
        names.add(input.nextLine());
    }
0

Java has fixed length array and it is not possible to change size of array dynamically. To do what you need there is java.util.ArrayList class.

(look at Reginol_Blindhop's answer. Regardless is it ArrayList or LinkedList code is the same).

But if you need array you can create new array with +1 size for every input, copy previous values there and put new into last element. To do that there is System.arraycopy method.

code may look like:

         String[] names = new String[1];

         for(int counter = 0; counter < 100; counter++){
                System.out.print("Enter name: ");
                String nextName = input.nextLine();

                String[] tempNames = new String[names.length + 1];
                System.arraycopy(names, 0, tempNames, 0, names.length);
                tempNames[names.length] = nextName;
                names = tempNames;
         }

PS. Of course for any solution it is better to use while loop and check if user finishes input by putting something special like "exit", "end", "bye", ":q" or whatever you'd like.

Vadim
  • 4,027
  • 2
  • 10
  • 26
0

You should use a List for something like this, not an array. As a general rule of thumb, when you don't know how many elements you will add to an array before hand, use a List instead. Most would probably tackle this problem by using an ArrayList.

joe
  • 1
  • 1