rmac
rmac

Reputation: 33

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.

Upvotes: 3

Views: 23642

Answers (5)

Lorie Zimmerman
Lorie Zimmerman

Reputation: 1

This worked for me.

import java.util.Scanner;
public class ParseStrings {
   public static void main(String[] args) {

      Scanner scnr = new Scanner(System.in); // Input stream for standard input
      Scanner inSS = null;              // Input string stream       
      String lineString = "";           // Input string   
      String firstWord = "";             // Word one
      String secondWord = "";             // word two
      boolean inputDone = false;
  
      while (!inputDone) {

         System.out.println("Enter input string: ");

         // Entire line into lineString
         lineString = scnr.nextLine();
  
         // Create new input string stream
         inSS = new Scanner(lineString);
     
         //Set the delimiter to "," and new line
         inSS.useDelimiter("[,\n]");
     
         if (lineString.equals("q")) {
            inputDone = true;
            break;
         }
     
         if (lineString.indexOf(",") == -1) {
            System.out.println("Error: No comma in string");
        
            continue;  
     
         }
         else {
  
            // Now process the line           
            firstWord = inSS.next();
            // Now process the line
            secondWord = inSS.next();
  
            System.out.println("First word: " + firstWord.trim().replace(",", ""));
            System.out.println("Second word: " + secondWord.trim().replace(",", "") + "\n\n");
         }   
     
      }
      return;
   }
}   

Upvotes: 0

Kris Kollman
Kris Kollman

Reputation: 1

The unit I was working on for this problem was about using the inSS, so I wanted to try and use it to solve the problem. I did get stuck constantly collecting the comma for the second word, but after consulting someone else was suggesting using a delimiter to get passed the comma. I did have to add a trim() command on the print lines to get rid of any white spaces around the words when they were captured by the inSS.##


import java.util.Scanner;


public class ParseStrings {
   public static void main(String[] args) {
      Scanner scnr = new Scanner(System.in);
      //Input string stream
       Scanner inSS = null;
    //Input string 
    String inputWords;
    // first word
    String firstWord;
    //Comma check;
    String commaCheck;
    //second word
    String secondWord;
    //flag to indicate next iteration
       boolean inputDone;
    
       inputDone = false;

    //prompt the user to input string 
    System.out.println("Enter input string: ");
    
    //take input data as long as "q" is not ent
    while (!inputDone){
    
        //entire line into inputWords
        inputWords = scnr.nextLine();
        
        //Init scanner object with string
        inSS = new Scanner(inputWords);

        //Set the delimiter to "," and new line
        inSS.useDelimiter("[,\n]");
   
        //process the line
        firstWord = inSS.next();
   
        //output parsed values
        if (firstWord.equals("q")){
            inputDone = true;
            break;
        }
        
        //comma check
        if(inputWords.indexOf(",") == -1){
            System.out.println("Error: No comma in string");
            System.out.println("Enter input string: ");
            continue;
        }
        else {
            secondWord = inSS.next();
            System.out.println("First word: " + firstWord.trim());
            System.out.println("Second word: " + secondWord.trim());
            System.out.println();
            System.out.println();
        }
        System.out.println("Enter input string: ");
                

   
    }

    }   
}

Upvotes: 0

matalco
matalco

Reputation: 11

I got this same problem in my class and it been a very challenging problem for me to figure out. I was able to get the correct answer using the code posted in here that only needed very slight modifications made to it. Thank you for the help. below is modified version of the above the code I used to get the correct answer.

import java.util.Scanner;

public class ParseStrings {
   public static void main(String[] args) {
      Scanner scnr = new Scanner(System.in);
      String userInput = "";
      boolean inputDone = false; 

      while (!inputDone) {
         System.out.print("Enter input string: \n");
         userInput = scnr.nextLine();

         if (userInput.equals("q")){
            inputDone = true;
            break;
         }

         if(userInput.indexOf(",") == -1){ //if comma is not found in the user input
         System.out.println("Error: No comma in string");
         continue;
         }


          else {
            String[] userArray = userInput.split(",");
            System.out.println("First word: " + userArray[0].trim());
            System.out.println("Second word: " + userArray[1].trim());
            System.out.println();
            System.out.println();
        }
      }


      return;
   }
}

Upvotes: 1

Papershine
Papershine

Reputation: 5223

import java.util.Scanner;

public class ParseStrings {
   public static void main(String[] args) {
      Scanner scnr = new Scanner(System.in);
      String userInput = "";
      boolean inputDone = false; 

      while (!inputDone) {
         System.out.print("Enter input string: \n");
         userInput = scnr.nextLine()


         if (userInput.equals("q")){
            System.out.println("First word: " + userInput);
            inputDone = true; 
         } else {
            String[] userArray = userInput.split(",");
            System.out.println("First word: " + userArray[0]);
            System.out.println("Second word: " + userArray[1]);
            System.out.println();
        }
      }


      return;
   }
}

Explanation: First, an object Scanner is created. Then, the user's input is stored in userInput. After that, java checks if the user entered q, if so, then end the application. Else, java splits the string into two words and then prints it.

Remember that understanding the code is a very important process in learning a programming language, so please, please understand the code and not just copy and paste it to submit as your homework.

Upvotes: 1

freedev
freedev

Reputation: 30067

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

Upvotes: 1

Related Questions