0
int i=0;
String x[]= new String[i];
while(true){
    if(x[i]!="stop") {
        x[i]=in.nextLine();
        i++;
        return;
    }
}

I want the user to input text hit enter, input some other text and hit enter etc. until the user types "stop". I then want the array x[i] to have all the different inputs to be stored as its elements.

NetBeans keep sending

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0 at app.App.main(App.java:46)

How can I fix this?

ROMANIA_engineer
  • 54,432
  • 29
  • 203
  • 199
  • 2
    In Java you can't compare strings by using the `==` and `!=` operators, you need to use the `equals(...)` method. – Titus Oct 21 '14 at 21:20
  • 1
    The error is exactly what it says: when you create `x`, `i` is holding `0`. If you want to dynamically resize your array, use an `ArrayList`, or in this situation probably a `LinkedList`. – Floegipoky Oct 21 '14 at 21:28

3 Answers3

1

I can't even begin to correct your code. To achieve what you want to do try this:

    Scanner in = new Scanner(System.in);
    ArrayList<String> list = new ArrayList<String>();
    String line;
    while (!(line = in.nextLine()).equals("stop")) {
        list.add(line);
    }
    in.close();
    System.out.println(list);
Titus
  • 22,031
  • 1
  • 23
  • 33
0

You've initialized the array to size 0 (which is what i starts as). So x[i] doesn't exist when you start to go through the loop.

I'd recommend using an ArrayList as detailed in this question: How to add new elements to an array?

x[i]!="stop"

Also won't evaluate true when the user enters stop, as it is comparing the object references, not the content of the string.

See this article on string comparison in Java: http://docs.oracle.com/javase/tutorial/i18n/text/collationintro.html

Community
  • 1
  • 1
Tom Elliott
  • 1,908
  • 1
  • 19
  • 39
0

You have ArrayIndexOutOfBoundsException because of this line:

String x[]= new String [i];    // here i = 0

Because you don't know the input size until the run time, you need a data structure that is more flexible regarding its size.


Use an ArrayList<String> instead of that array:

public static void main(String[] args) {

    ArrayList<String> x = new ArrayList<String>();

    String line = "";
    Scanner in = new Scanner(System.in);

    while(true){
        line = in.nextLine();
        if ("stop".equals(line)) {
            break;
        }
        x.add(line);
    }
    in.close();

    System.out.println(x);  // print the result
}

or using try-with-resources from Java 7:

    ArrayList<String> x = new ArrayList<String>();

    try(Scanner in = new Scanner(System.in)) {
        String line = "";
        while(true){
            line = in.nextLine();
            if ("stop".equals(line)) {
                break;
            }
            x.add(line);
        }
    }
ROMANIA_engineer
  • 54,432
  • 29
  • 203
  • 199