Skip to content
Advertisement

how to define an array without a defined length of it

The question is: get a score of 10 peoples; then you need to ask each one with a score higher than 80 if he would want to continue studying ‘y’ for yes and ‘n’ for no. Next you need to get their location in the array so if person number 5 array[5]=90 and answers ‘y’ it will make a new array with newarray[1]=[5(his location)]

My question is how to define the newarray without knowing its length(how many ‘y’ there would be). EDIT:

import java.util.Scanner;
public class p44_52 {
static Scanner reader = new Scanner(System.in);
static void input(int []a)
{
    for(int i=0; i<a.length;i++){
        System.out.println("Write an score of a student");
        a[i]= reader.nextInt();
    }
}
    

static void output(int []b)
{
    for (int i =0; i<b.length;i++)
    {
        System.out.println("serial number of who choose to continue and score above 80  "+ b[i]);
    }
}

public static void main(String[]args){
    
    char c = 'g';
    int count =0;
    int []score = new int[10];
    kelet(score);

    for(int i=0; i<score.length;i++)
    {
        if(score[i]>80)
        {
            System.out.println("Studnet number "+i+ " Do you want to continue?");
            c = reader.next().charAt(0);
            if(c == 'y'){
                //Here i want to make the new array(length isn't known) for their locationnumbers
            }
        }
    }
    
    
}

}

Advertisement

Answer

You can create a temporary array with the same size as the full list (because you know that’s the largest it could need to be) and populate it with as many students as choose to continue. There will probably be fewer elements actually in the temporary array than it can hold because some students won’t continue, so then you can create a new array that’s the right size (now that you know it) and use System.arraycopy() to copy all of the elements into the right-size array.

It’s not the most efficient way to do it, but it’s not terrible (it just uses one extra array allocation and copy operation) and it’s certainly good enough for homework. And it doesn’t use anything other than arrays.

In general, this is a technique you’ll use from time to time as you write programs: if there’s something you can’t do until you’ve done some operation, then look for a way to break the operation into multiple steps so you can rearrange steps in an order that is possible but still yields the same result. Better still is to find a different data structure that meets your needs (as ArrayList will, since its capacity can be grown at runtime), but there will be times when you can’t just drop in a different data structure, and this approach of breaking the problem down and rearranging steps can be useful then.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement