简体   繁体   中英

I am stuck on my Java homework Parsing Strings

I am somewhat lost on what to do.

There are 4 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

I've figured out everything out but can't figure out the second part. I don't exactly know how to do the code for does not contain comma.

Here's my code:

import java.util.Scanner;

public class ParseStrings {

public static void main(String[] args) {
    Scanner scnr = new Scanner(System.in);
    String lineString = "";
    int commaLocation = 0;
    String firstWord = "";
    String secondWord = "";
    boolean inputDone = false;

    while (!inputDone) {
        System.out.println("Enter input string: ");
        lineString = scnr.nextLine();


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

        else {
        commaLocation = lineString.indexOf(',');
        firstWord = lineString.substring(0, commaLocation);
        secondWord = lineString.substring(commaLocation + 1, lineString.length());

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


    return;
    }
}

Let's have a look at the line:

commaLocation = lineString.indexOf(',');

in case there is no comma, .indexOf() returns -1 - you can take advantage of it and add an if condition right after this line and handle this case as well!

You can use :

if (input.matches("[^,]+,[^,]+")) {//If the input match two strings separated by a comma

    //split using this regex \s*,\s* zero or more spaces separated by comman
    String[] results = input.split("\\s*,\\s*");

    System.out.println("First word: " + results[0]);
    System.out.println("Second word: " + results[1]);
} else {
    //error, there are no two strings separated by a comma
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM