Exception in thread "main" in String array

Asked

Viewed 49 times

1

I would like to add the text inserted by the user in a vector position, but it is giving error... why?

public static void main(String[] args) {
    int cont=0;
    String inserida = JOptionPane.showInputDialog("Insira a " +cont+ " String: "
            + "\n 0 encerra.");
    String [] vetString = null;
    while (!inserida.equals("0")) {
        cont++;
        vetString[cont] = inserida;
    }

    //linearString(vetString[], inserida);

}

}

  • is probably a nullpointer, because you are putting vetstring = null, when creating an array it needs to be initialized, eg: String[] vetString = new String[20];

  • Speak, Lucas, I appreciate the help, I did that, but now it continues giving "Exception in thread "main" java.lang.Arrayindexoutofboundsexception: 2 blogat Professor.VetorDeStrings.main(Vetordestrings.java:25) "

  • Arrayindexoutofboundsexception means that you are trying to access a vector address that does not exist, if for example you do String[] vetString = new String[20] and then try to access position 22 (vetString[22])

  • I figured it was exactly that, but even with the proposal you suggested, the error persists... even to insert the row from position 1 of the Array, even though I declared it with size 10000.

1 answer

0


Your code has some problems, among which:

  • The stopping condition of the while is that the value inserted is equal to 0, but the value is only reported before the loop. So the loop will never end;

  • Your array is not initialized at any time, so if you try to manipulate it, you will have the exception NullPointerException launched.

So it seems you want to insert into all the elements of array the same value. Taking this into account you can change your code to the following:

public static void main(String[] args) {
  final int TAMANHO = 1000;
  int cont = 0;
  String inserida = JOptionPane.showInputDialog(String.format("Insira a %s String:\n 0 encerra.", cont));
  String[] vetString = new String[TAMANHO];

  while (!inserida.equals("0") && cont < TAMANHO) {
    vetString[cont] = inserida;
    cont++;
  }

  //linearString(vetString[], inserida);
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.