我被困在我的Java作业Parsing Strings上

时间:2017-12-04 17:28:50

标签: java string parsing

我有点迷失了该怎么做。

共有4个部分。

  1. 提示用户输入包含两个以逗号分隔的字符串的字符串。
  2. 如果输入字符串不包含逗号,则报告错误。继续提示,直到输入有效字符串。注意:如果输入包含逗号,则假设输入还包含两个字符串。
  3. 从输入字符串中提取两个单词并删除所有空格。将字符串存储在两个单独的变量中并输出字符串。
  4. 使用循环,扩展程序以处理多行输入。继续,直到用户输入q退出。
  5. 最终结果应打印如下:

    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
    

    我已经弄清楚了所有事情,但无法弄清楚第二部分。我不知道怎么做代码不包含逗号。

    这是我的代码:

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

2 个答案:

答案 0 :(得分:1)

让我们来看看这一行:

commaLocation = lineString.indexOf(',');

如果没有逗号,.indexOf()会返回-1 - 您可以利用它并在此行之后添加if条件并处理此案例!

答案 1 :(得分:0)

您可以使用:

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
}