3

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.

1
  • You haven't declared a variable to be s, how could java split it? Commented Feb 4, 2017 at 1:14

5 Answers 5

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
Sign up to request clarification or add additional context in comments.

1 Comment

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

2 Comments

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.
@rmac Hope this helped you! If this is the right answer, you can click on the tick sign on the left
1

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;
   }
}

1 Comment

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 :)
0

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: ");
                

   
    }

    }   
}

1 Comment

Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.
0

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;
   }
}   

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.