I am working on a homework assignment and unable to find the answer in my online text book or anywhere else.
My homework question is four parts:
Prompt the user for a string that contains two strings separated by a comma.
Report an error if the input string does not contain a comma. Continue to prompt until a valid string is entered. Note: If the input contains a comma, then assume that the input also contains two strings.
Extract the two words from the input string and remove any spaces. Store the strings in two separate variables and output the strings.
Using a loop, extend the program to handle multiple lines of input. Continue until the user enters q to quit.
Final outcome should print out as follows: Enter input string: Jill, Allen First word: Jill Second word: Allen
Enter input string: Golden , Monkey First word: Golden Second word: Monkey
Enter input string: Washington,DC First word: Washington Second word: DC
Enter input string: q
My code output is incorrect. I do not know how to make the automatic , not show after my first word or show up as my second word. I have tried using
String [] array = s.split(",); and the class program does not recognize this command and errors out.
This is my code:
import java.util.Scanner;
public class ParseStrings {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
Scanner inSS = null;
String firstWord = " ";
String secondWord = "";
String lineString = "";
boolean inputDone = false;
while (!inputDone) {
lineString = scnr.nextLine();
inSS = new Scanner(lineString);
firstWord = inSS.next();
System.out.print("Enter input string: \n");
if (firstWord.equals("q")){
System.out.println("First word: " + firstWord);
inputDone = true;
} else {
secondWord = inSS.next();
System.out.println("First word: " + firstWord);
System.out.println("Second word: " + secondWord);
System.out.println();
}
}
return;
}
}
How can I code this string to include and exclude the comma and print out the error. I am not understanding what I need to do.
s, how could java split it?