0

In a method I created I am trying to create is meant to return an array of user inputted strings. The issue that I am having it the compiler is saying that userData may not be initialized at userData[i]=tempData; and at return userData;. I am unsure why this error is occuring, and would like some feedback.

public String[] getStringObj() {
    int i = 0;
    String tempData;
    String[] userData;
    Boolean exitLoop = false;
    System.out.println("Please list your values below, separating each item using the return key.  To exit the input process please type in ! as your item.");
    do {
        tempData = IO.readString();
        if (tempData.equals("!")) {
            exitLoop=true;
        } else {
            userData[i] = tempData;
            i++;
        }
    } while (exitLoop == false);
    return userData;
}
nonterrorist
  • 103
  • 1
  • 7
  • 1
    possible duplicate of [Variable might not have been initialized error](http://stackoverflow.com/questions/2448843/variable-might-not-have-been-initialized-error) – epoch Oct 24 '12 at 05:38
  • compiler is correct this time. _variable is not initialized_ – manas Oct 24 '12 at 05:52

3 Answers3

0

Your userData is not initilaized and you are attempting to use it here userData[i]=tempData; before initialization.

Initialize it as

String[] userData = new String[20]; 

//20 is the size of array that I specified, you can specify yours

Also in your while condition you can have while(!exitLoop) instead of while(exitLoop==false)

Abubakkar
  • 15,488
  • 8
  • 55
  • 83
  • I do not want a limit as to how many String values the user can input. Is there a way I can put in an arbitrarily large number for the length and then re-size to remove the tailing null values? – nonterrorist Oct 24 '12 at 05:42
  • For that you better use `ArrayList`- As elements are added to an `ArrayList`, its capacity grows automatically. – Abubakkar Oct 24 '12 at 05:44
0

You didn't initialize the String[]. Just do String[] userData = new String[length]. If you are unsure of the length, you may just want to use an ArrayList<String>.

awolfe91
  • 1,627
  • 1
  • 11
  • 11
0

In the interests of improving code quality:

  1. You don't need that exitLoop flag; just do

    while(true) {
        String input = IO.readString();
        if(input.equals("!")) {
            break;
        }
        /* rest of code */
    }
    
  2. Since you seem like you want to just add stuff to an array without bounds, use an ArrayList instead of an array (added bonus, this gets rid of i too):

    List<String> userData = new ArrayList<String>();
    ...
    userData.add(line);
    

If you do these two things, your code will be much more concise and easy to follow.

nneonneo
  • 171,345
  • 36
  • 312
  • 383