0

im trying to do this for fun but i cant figure out why i keep getting "null" instead of previous entry.

ps. this isnt homework
Thank you

public class GetUser {


  public static void main(String[] args) { 

    String name;
    String a [];
    char x='y';
    int i;
    int n=1;
  do{



      System.out.println();
      System.out.println("Please enter a name");


      a = new String [n];
      a[n-1]=  ITI1120.readString();


     System.out.println ();
     System.out.println("Do you want to add more names? (y/n)");
     x= ITI1120.readChar();


      System.out.println("Your list so far is:");
     for(i=0; i<n; i++){
       System.out.println(a[i]);
     }


     n=n+1;

     }while(x=='y');
    }


  }
2
Contributors
4
Replies
22
Views
3 Years
Discussion Span
Last Post by aldahoudi
Featured Replies
  • That's a very good question! You set the size of an array when you create it, and it can never be changed. So your main options are: 1. Ask the user how many numbers they want to enter, and use that to create an array of the right size 2. … Read More

0

Line 19. On each pass of the loop you create a new array (which will have all nulls as its data) and thus lose all the previous data. You need to create the array just once, before entering the loop.

0

then how can i have an array that is as big as the number of entered strings ?

1

That's a very good question! You set the size of an array when you create it, and it can never be changed. So your main options are:
1. Ask the user how many numbers they want to enter, and use that to create an array of the right size
2. Guess a reasonably large size, but then if they enter too many numbers you create a larger array, copy the existing entries into it, then use the new array and let the old one be garbage collected.
3. Use an ArrayList instead of an array - internally it implements option 2 for you. Google for examples and tutorials if necessary.

This article has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.