【问题标题】:I am stuck on my Java homework Parsing Strings我被困在我的 Java 作业解析字符串上
【发布时间】:2017-12-05 01:43:15
【问题描述】:

我有点不知所措。

有 4 个部分。

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

最终结果应打印如下:

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

【问题讨论】:

标签: java string parsing


【解决方案1】:

让我们看看这条线:

commaLocation = lineString.indexOf(',');

如果没有逗号,.indexOf() 返回-1 - 您可以利用它并在此行之后添加一个if 条件并处理这种情况!

【讨论】:

  • 谢谢,我以为是-1,但不知道放在哪里
【解决方案2】:

你可以使用:

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
}

【讨论】:

    猜你喜欢
    • 2017-09-26
    • 1970-01-01
    • 2018-07-05
    • 2018-05-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多