5.6 Warm up: Parsing strings (Java)

5.6 Warm up: Parsing strings (Java)

Answer

import java.util.Scanner;
public class ParseStrings {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);//to read input from user
String str;//to hold strig entered by user
System.out.println("Enter input string");//asking user to enter a string
str=sc.nextLine();//reading into str
while(!str.equalsIgnoreCase("q"))
{
while(!str.contains(","))//checking valid word or not
{
System.out.println("Error: No comma in string");
System.out.println("Enter input string");
str=sc.nextLine();
}
//extracting the two words and printing
String word1=str.substring(0, str.indexOf(","));
String word2=str.substring(str.indexOf(",")+2);
System.out.println("First word: "+word1);
System.out.println("Second word: "+word2);
System.out.println("Enter input string");//asking user to enter a string
str=sc.nextLine();//reading into str
}
}
}

Leave a Reply

Your email address will not be published. Required fields are marked *

Related Posts