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
5 Antworten
+ 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
0
You’re on the right track! The key idea is that you need to count how many words the user typed. The easiest way to do that is to split the input by spaces and check the length of the resulting array. For example : System.out.print("Enter a name: "); String name = sc.nextLine().trim(); // trim() removes leading/trailing spaces String[] parts = name.split("\\s+"); // split on one or more spaces // Step 4: validate the word count if (parts.length < 2 || parts.length > 3) { System.out.println("Error: Please enter a name with 2 or 3 words only."); return; // stop the program } After validation, you can safely extract names: String firstName = parts[0]; String middleName = (parts.length == 3) ? parts[1] : ""; String lastName = parts[parts.length - 1]; System.out.println("First name: " + firstName); if (!middleName.isEmpty()) { System.out.println("Middle name: " + middleName); } System.out.println("Last name: " + lastName);
14th Nov 2025, 3:40 PM
Avinash Ranjan