5.6 Warm up: Parsing strings (Java)
(1) Prompt the user for a string that contains two strings separated by a comma. (1 pt)
Examples of strings that can be accepted:
Jill, Allen
Jill , Allen
Jill,Allen
Ex:
Enter input string: Jill, Allen
(2) 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. (2 pts)
Ex:
Enter input string: Jill Allen Error: No comma in string Enter input string: Jill, Allen
(3) Extract the two words from the input string and remove any spaces. Store the strings in two separate variables and output the strings. (2 pts)
Ex:
Enter input string: Jill, Allen First word: Jill Second word: Allen
(4) Using a loop, extend the program to handle multiple lines of input. Continue until the user enters q to quit. (2 pts)
Ex:
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
Expert Answer
Tested on Eclipse with Java-8
package stringclass;
import java.util.Scanner;
// TODO: Auto-generated Javadoc
/**
* The Class ParsingString.
* @author Lalchand Mali.
*/
public class ParsingString {
/**
* The main method.
*
* @param args the arguments
*/
public static void main(String[] args) {
String userInput;
Scanner input = new Scanner(System.in);
/**
* Taking input from user
*/
System.out.print(“Enter input string: “);
userInput = input.nextLine();
/**
* Loop continue until userInput not equal to q
*/
while(!userInput.equals(“q”)) {
/**
* If input contain comm then split it
* otherwise print error with message
* and continue for user input
*/
if(userInput.contains(“,”)){
String[] arr = userInput.split(“,”);
System.out.println(“First Word:” + arr[0].trim());
System.out.println(“Second Word:” + arr[1].trim());
} else{
System.out.println(“Error: No comma in string”);
}
System.out.print(“Enter input string: “);
userInput = input.nextLine();
}
/**
* closing Scanner stream.
*/
if(input!=null){
input.close();
}
}
}
/**************************Output***************************/
Enter input string: Jill Allen
Error: No comma in string
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