2

First off, I am brand new to both Java and to this website. I am going to ask my question as thoroughly as I can. However, please let me know if you think I left something out.

I am working on a school assignment, and I am stuck on the second portion of it. I am able to prompt the user, but can not for the life of me, figure out how to ensure that the input string contains a comma. I did try searching this site, as well as Googling it, and haven't been able to find anything. Perhaps I am not wording the question appropriately.

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

So far I have this:

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 = "";                // Holds line of text
    String firstWord = "";                 // First name
    String secondWord = "";                  // Last name
    boolean inputDone = false;             // Flag to indicate next iteration

    // Prompt user for input
    System.out.println("Enter string seperated by a comma: ");

    // Grab data as long as "Exit" is not entered
    while (!inputDone) {

        // Entire line into lineString
        lineString = scnr.nextLine();

        // Create new input string stream
        inSS = new Scanner(lineString);

        // Now process the line
        firstWord = inSS.next();

        // Output parsed values
        if (firstWord.equals("q")) {
            System.out.println("Exiting.");

            inputDone = true;

        if else (lineString != ",") {     // This is where I am stuck!
            System.out.print("No comma in string");
        }
        } else {
            secondWord = inSS.next();


            System.out.println("First word: " + firstWord);
            System.out.println("Second word: " + secondWord);

            System.out.println();
        }
    }

    return;
}

}

I know my "if else" is probably not correct. I just don't know where to begin for this particular command. Unfortunately my eBook chapter did not cover this specifically. Any thoughts would be greatly appreciated. Thank you so much!

SallyJane0118
  • 29
  • 1
  • 2
  • 1
    if(lineString.contains(","){ do something – ivan Sep 22 '16 at 22:40
  • 1
    Have you tried running it? What happens? Does it work or do something unexpected? When explaining a problem, tell us what you did, what should happen, and what actually happened. – Jim Garrison Sep 22 '16 at 22:40
  • There is no such statement as `if else` in Java. It's `if (...) { ... } else { ... }`. Beyond that, look at `String.split()` to split the string at a comma. – Jim Garrison Sep 22 '16 at 22:41
  • 1
    Possible duplicate of [How to check if a String contains another String in a case insensitive manner in Java?](http://stackoverflow.com/questions/86780/how-to-check-if-a-string-contains-another-string-in-a-case-insensitive-manner-in) – nhouser9 Sep 22 '16 at 22:45

3 Answers3

0

I suspect you want to assert if the input contains a comma, and at least one letter either side. For this you need regex:

if (!input.matches("[a-zA-Z]+,[a-zA-Z]+")) {
    System.out.print("Input not two comma separated words");
}
Bohemian
  • 412,405
  • 93
  • 575
  • 722
0

Since you are looking for a string with a comma in it and you want to get the string “Before” the comma and the string “After” the comma, then string.split(‘,’) is what you want. Asking if the string “Contains” a comma gives you no information about the string before or after the comma. That’s where string.split() helps. Since you don’t care “Where” the comma is you simply want the string before the comma and the string after the comma. The string.split(‘,’) method will return a string array containing the strings that are separated by commas (in your case) or any character. Example:

string myString = “firstpart,secondpart”;

… then

string[] splitStringArray = myString.Split(‘,’)

This will return a string array of size 2 where

splitStringArray[0] = “firstpart”
splitStringArray[1] = “secondpart"

with this info you can also tell if the user entered the proper input… i.e…

if the splitStringArray.Length (or Size) = 0, then the user did not input anything, if the splitStringArray.Length (or Size) = 1 then the user input 1 string with no commas… might check for exit here. If the splitStringArray.Length (or Size) = 2 then the user input the string properly. if the splitStringArray.Length (Size) > 2 then the user input a string with more than 1 comma.

I hope that helps in describing how string.split works.

Your code however needs some work… without going into much detail below is a c# console while loop as an example:

inputDone  =  false;
while (!inputDone)
{
  Console.Clear();
  Console.WriteLine("Enter string seperated by a comma: ");
  lineString = Console.ReadLine();
  string[] splitStringArray = lineString.Split(',');

  // check for user to quit
  if (splitStringArray.Length == 1)
  {
    if (splitStringArray[0] == "q")
    {
      inputDone = true;
      Console.Clear();
    }
    else
    {
       // 1 string that is not "q" with no commas
    }
  }

  if (splitStringArray.Length == 2)
  {
    // then there are exactly two strings with a comma seperating them
    // or you may have ",string" or "string,"
    Console.WriteLine("First word: " + splitStringArray[0]);
    Console.WriteLine("Second word: " + splitStringArray[1]);
    Console.ReadKey();
  }
  else
  {
    Console.WriteLine("Input string empty or input string has more than two strings seperated by commas");
    Console.ReadKey();
  }

}   

Hope that helps.

JohnG
  • 9,259
  • 2
  • 20
  • 29
0

This worked for me:

import java.util.Scanner;
import java.io.IOException;

public class ParseStrings {

    public static void main(String[] args) {

        Scanner scnr = new Scanner(System.in);
        Scanner inSS = null;
        String lineString = "";
        String firstWord = "";
        String nextWord = "";

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

        while (lineString.matches("q") == false) {
            lineString = scnr.nextLine();
            lineString = lineString.replaceAll(",",", ");
            inSS = new Scanner(lineString);
            int delimComma = lineString.indexOf(",");

            if ((delimComma <= -1) && (lineString.matches("q") == false)) {
                System.out.println("Error: No comma in string");
                System.out.println("Enter input string: ");
            }

            else if ((delimComma <= -1) && (lineString == null || lineString.length() == 0 || lineString.split("\\s+").length < 2) && (lineString.matches("q") == false)) {
                System.out.println("Error: Two words");
                System.out.println("Enter input string: ");
            }

            else if (lineString.matches("q") == false) {
                firstWord = inSS.next();
                nextWord = inSS.nextLine();
                System.out.println("First word: " + firstWord.replaceAll("\\s","").replaceAll("\\W","").replaceAll("\\n",""));

                System.out.println("Second word: " + nextWord.replaceAll("\\s","").replaceAll("\\W","").replaceAll("\\n",""));

                System.out.println("\n");

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

        return;
    }

}
Chris Warrick
  • 1,571
  • 1
  • 16
  • 27