-4

This is excercise from my classes. I passed but I'm receiving null from last println's. Could you please help with examples? I want to understand code rather than make it work ;)

Thank you!

import java.io.IOException;
import java.util.Arrays;
import java.util.Scanner;
public class Main {

    public static void main(String[] args) throws IOException {
        String[] namesWomen = new String[5];
        String[] namesMen = new String[5];
        String[] names = new String[5];
        Scanner reading = new Scanner(System.in);

        for (int i = 0; i < 5; i++) {
            System.out.println("Enter the name: ");
            names[i] = reading.nextLine();
            System.out.println("Thank you!");

        }
        for(int i=0; i<5;i++) {
            var name = names[i];
            if (name.charAt(name.length() - 1) == 'a') {
                System.out.println("woman");
                namesWomen[namesWomen.length- 1] = name;
            } else {
                System.out.println("men");
                namesMen[namesMen.length- 1] = name;
            }
        }
        System.out.println(Arrays.toString(namesMen));
        System.out.println(Arrays.toString(namesWomen));
    }
}
Pietia
  • 1
  • 1
  • Possible duplicate of [What is a debugger](https://stackoverflow.com/questions/25385173/what-is-a-debugger-and-how-can-it-help-me-diagnose-problems) – Hovercraft Full Of Eels Jan 15 '22 at 00:03
  • Does this answer your question? [What is a debugger and how can it help me diagnose problems?](https://stackoverflow.com/questions/25385173/what-is-a-debugger-and-how-can-it-help-me-diagnose-problems) – user11717481 Jan 15 '22 at 11:03

1 Answers1

1

When you instantiate a new array as you did for namesWomen and namesMen, all of its elements are initialized to null. It looks like, in your code, there's only one place where you're changing a value within namesWomen:

namesWomen[namesWomen.length- 1] = name;

and one place where you're changing a value within namesMen:

namesMen[namesMen.length- 1] = name;

Both times, you're only changing the last element in the list, so all of the other elements remain null throughout the entire program.

esramish
  • 197
  • 5