Search code examples
javaarraysloopslistings

Array only printing final element JAVA?


private static String[] nameArray;

public static void newPerson() {
 Scanner scanner = new Scanner(System.in);

 System.out.print("Name: ");
 name = scanner.nextLine();
 nameArray = new String[] {
  name
 };

}

public static void personInfo() {
 System.out.print("Current Persons : \n");
 StringBuilder arrayOutput = new StringBuilder();

 for (String something: nameArray) {
  arrayOutput.append(something);
 }

 String text = arrayOutput.toString();
 System.out.println(text);
}

Hello all thanks in advance for your help I m having a problem I have a loop that call a method once a number is entered in that method is this:

So my question whenever I call the newPerson method and enter a name instead of having all the names stored and in the array and later printed, the personInfo method only prints the final name that I enter in the array why is it not displaying all the names?


Solution

  • You're replacing the nameArray entirely after each input. You have to add it to your array. But it is easier to use 'ArrayList's in this case.

    Building on your provided code:

    private static ArrayList<String> nameArray = new ArrayList<>();
    
    public static void newPerson() {
           Scanner scanner = new Scanner(System.in); 
    
           System.out.print("Name: ");
           name = scanner.nextLine(); 
           nameArray.add(name);
    }
    
    public static void personInfo() {
        System.out.print("Current Persons : \n"); 
        StringBuilder arrayOutput = new StringBuilder();
        for ( String something  : nameArray) {
            arrayOutput.append(something);
        }  
        String text = arrayOutput.toString();
        System.out.println(text); 
    }