Pouria Mohseni February 2016

How can I fix this code? i use integer variable for array index

** does not work as expected and I don't know what's wrong.

i use integer variable for array index and in a method i Determine the value for variable **


import java.util.Scanner;

public class Test {

static Scanner key = new Scanner (System.in);
static int count = 0;
static int nameNum;
static String[] name = new String [nameNum];

public static void main (String [] args){

    readNameNum();
    readName();
    showNameList();


}

public static int readNameNum (){

    System.out.println("Enter number of names");
    System.out.print("> ");
    nameNum = key.nextInt();
    return nameNum;

}

public static void readName (){

    System.out.println("Enter "+nameNum+" names");

    for (int i = 0; i < nameNum; i++){

        count++;

        System.out.print("N"+count+": ");
        name [i] = key.next();

    }


}

public static void showNameList (){

    for (int i = 0; i < name.length; i++){

        System.out.println(name [i]);
    }
}

}

Answers


Abdelhak February 2016

Try to initialize this nameNum variable before use it:

  static int nameNum= 20;// ex 20

Or if you want i suggest to use something like this:

 static String[] name = null;
 public static void main (String [] args){

    name = new String [readNameNum()];
    readName();
    showNameList();
 }


Peter Lawrey February 2016

You create the array of String before you know how many elements it should have.

static int nameNum; // == 0
static String[] name = new String [nameNum]; // doesn't magically change size.

nameNum = key.nextInt(); // doesn't change the `name`

I suggest you only create the array once you know what size it should be i.e. after you have read it.

Before you fix this bug, you should step through your program in your debugger to confirm this is the problem.

Post Status

Asked in February 2016
Viewed 2,365 times
Voted 7
Answered 2 times

Search




Leave an answer