1

Similar to my old question. Is there a way I can store what the user inputs into an array so I can call it via stringName[1] or stringName[2]? I am not well versed in java split. for example, if I had

System.out.println ("A sentence or your full name please" );
for (int j = 0; j < arrayTwo.length; j++){
array[j]= sc.nextLine();
System.out.println(array[0]);

this only prints out the first name

if the user inputs "John Will Smith" and later i want to print out

System.out.println (+firstName);
System.out.println (+middleName);
System.out.println (+lastName);

how do i go about individually updating the array or split it in a way I can grab what the user inputted?

River
  • 21
  • 3

1 Answers1

0

Use of a for loop seems useless here. Read the string as a line and then split it by white space. Check the below code:

public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    System.out.println("A sentence or your full name please");
    String fullName = scanner.nextLine(); //Read the full name
    String[] nameArray = fullName.split("\\s+"); //Split the full name by white spaces and insert it to array
    for (String name : nameArray) { //Print names in array
        System.out.println(name);
    }
}
Anuradha
  • 570
  • 6
  • 20