Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to parse strings in Java?

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:

  1. Prompt the user for a string that contains two strings separated by a comma.

  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.

  3. Extract the two words from the input string and remove any spaces. Store the strings in two separate variables and output the strings.

  4. 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.

like image 779
rmac Avatar asked Apr 01 '26 07:04

rmac


1 Answers

I don't want write the code for the solution. Just give you some input to arrive at right answer by yourself. It is your exercise after all.

  1. You do not need to use two Scanner one is enough.
  2. Check the variable lineString after the execution of scnr.nextLine()
  3. The String method split usually helps to figure out
like image 122
freedev Avatar answered Apr 03 '26 20:04

freedev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!