0

Java homework help

I am working on a homework assignment for my Java class and I am stuck on one of the steps. Here's what it says: "Step 4: If the user enters fewer than two words or more than three words, display an error message. For simplicity, you can assume that each part of a name consists of a single word." I know how to write if statements that give error messages, I just don't know how to translate that in a way that basically says "if words < 2 or words > 3, display error message". Here's the code I have so far: import java.util.Scanner; import java.lang.String; public class NameParserApp { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.print("Enter a name: "); String name = sc.nextLine(); int index = name.indexOf(" "); //step 2: add code that separates the name into two or three strings depending on whether the user entered a name with two words or three String firstName = name.substring(0, index); String middleName = name.substring(index + 1); String lastName = name.substring(index + 2); //step 3: display each word of the name on a separate line System.out.println("First name: " + firstName); System.out.println("Middle name: " + middleName); System.out.println("Last name: " + lastName); //step 4: if the user enters fewer than two words or more than three words, display an error message } }

4th Feb 2022, 7:37 PM
Taylor Frye
4 Respostas
+ 2
Taylor Frye Here is the solution and no need to get index for names even you can get by accessing with index from array https://code.sololearn.com/cspW80LwXNEJ/?ref=app
4th Feb 2022, 7:49 PM
A͢J
A͢J - avatar
+ 3
Taylor Frye You can split entered name which will give you a string array and after getting length of that array you can throw error message.
4th Feb 2022, 7:41 PM
A͢J
A͢J - avatar
+ 1
Thanks AJ
4th Feb 2022, 7:55 PM
Taylor Frye
0
AJ, ok I'll give that a try
4th Feb 2022, 7:46 PM
Taylor Frye