How to parse strings in Java?

10,196

Solution 1

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

Solution 2

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.

Share:
10,196
rmac
Author by

rmac

Updated on June 27, 2022

Comments

  • rmac
    rmac almost 2 years

    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.

  • rmac
    rmac about 7 years
    Thank you for your help but I still do not understand. I did manage to remove the last character so the comma input is not automatic and add a line to out put the Error message. I also need this to loop more for the assignment, so I will have to revisit my code since it is not looping.
  • rmac
    rmac about 7 years
    Thank you for the detailed information. I see how I can use arrays instead and then add to make the additional Error: No comma in string.
  • Papershine
    Papershine about 7 years
    @rmac Hope this helped you! If this is the right answer, you can click on the tick sign on the left
  • Scratte
    Scratte about 4 years
    Your code works :) I just want to add that there's no reason so use both the inputDone variable and the break; because break will take the code out of the while-loop no matter the condition. So you can use while(true) with the break and remove the variable. Or you can keep the variable and use it in the while ()-loop and replace break; with continue;. Note: If you only enter a , or anything, you get an error (But the assignment says it's OK). You can also fix that with exception-handling :)