【问题标题】:How to parse a String in Java without using .parse()?如何在不使用 .parse() 的情况下解析 Java 中的字符串?
【发布时间】:2017-11-14 18:25:05
【问题描述】:

我正在尝试编写一个程序,它将接受一个字符串并将其解析为两个输出,分隔符是一个逗号。它循环直到用户输入字符“q”。

即:控制台提示输入一个输入,用户输入“first, second”,然后输入“q”作为第二个提示,输出将是:

Enter input string:
First word: first
Second word: second

Enter input string:

如果输入中没有逗号,则抛出错误并再次提示

即用户输入“第一秒”,输出将是:

Enter input string:
Error: No comma in string
Enter input string:

以下是我目前所拥有的:

import java.util.Scanner;

public class ParseStrings {
   public static void main(String[] args) {
         Scanner scnr = new Scanner(System.in); // Scanner for standard input
         Scanner inSS = null;                   // Scanner to write input to buffer
         String firstWord = "";                 // First word string
         String secondWord = "";                // Second word string
         String userInput = "";                 // Input from prompt
         int i = 0;                             // Loop iterator
         boolean inputDone = false;             // Boolean to repeat while loop
         boolean hasComma = false;              // Boolean to check for comma

         // Do while inputDone is false
         while (!inputDone) {

            //Prompt user to input a string
            System.out.println("Enter input string: ");

            // Write string to userInput
            userInput = scnr.nextLine();

            // Exit program if user inputs q
            if((userInput.equals("q"))) {
               inputDone = true;
               break;
            }
            else{

               // Write userInput to buffer
               inSS = new Scanner(userInput);

               // Write first word from buffer
               firstWord = inSS.next();

               // Loop through first word string
               for (i = 0; i < firstWord.length(); ++i) {

                  // If char is a comma, write everything after to secondWord and set inputDone to true
                  if(firstWord.charAt(i) == ',') {
                     secondWord = inSS.next();
                     hasComma = true;
                  }
               }

               // If hasComma is false, return error
               if (!hasComma){
                  System.out.println("Error: No comma in string");
               }
               // Else print first word and second word
               else {
                  System.out.println("First word: " + firstWord);
                  System.out.println("Second word: " + secondWord);
                  System.out.println("");
                  System.out.println("");
               }
            }
         }
        return;
       }
    }

问题:

  • 我不知道如何从输出中删除逗号
  • 如果没有空格则会出错
  • 如果第一个单词和逗号之间有空格,它会写入 firstWord,但不会覆盖 secondWord 的先前值(如果是给定的第一个输入,则会出错)
  • 我正在学习初学者的 Java 课程,我们还没有学习 .parse() 方法,所以目前还不是真正的选择。

提前谢谢你!

【问题讨论】:

    标签: java parsing


    【解决方案1】:

    尝试使用字符串拆分。

    String str="first, second";
    String[] arr=str.split(",");
    if(arr.length == 2) {
        System.out.println("First :" + arr[0]);
        System.out.println("Second :" + arr[1]);
    } if(arr.length > 2) {
        System.out.println("More than 1 comma used.");
    } else {
        System.out.println("Error. No comma found.");
    }
    

    您可以使用 trim() 以防您的字符串在逗号周围有任何空格。

    【讨论】:

    • 根据提问,他说他在一个字符串中有两个部分,分隔符为逗号。所以这应该有效。或者您可以添加另一个 if 检查,并通知用户他使用了多个逗号。
    • 我想我对您帖子的编辑已经解决了这个问题。只需为arr.length 添加&gt;= 而不是==
    • 我认为条件长度 == 2 是正确的。如果可以将其拆分为多个部分,则考虑到问题的描述,这将是违规行为。
    • 嘿,我只是在处理可能发生的任何异常。毕竟,用户将输入值,他/她/它可能会输入一些愚蠢的东西:)
    【解决方案2】:

    所以我所做的可能是最懒惰和最菜鸟的方法,但它确实有效。

    使用 for 循环检查字符串中每个字符的逗号。

    char ch;
    String str = "";
    
    if(userInput.charAt(userInput.length()-1) == ',')
        System.out.println("Error. You must have a comma here.");
    else {
    for(int i = 0; i < userInput.length(); i++)
    {
        ch = userInput.charAt(i);
        if(ch != ',')
            str += ch;
        else
        {
            firstWord = str;
            secondWord = userInput.substring(i+1);
            break;
        }
    }
    }
    

    如果所选字母不是逗号,则将其添加到临时字符串中。

    如果是逗号,则临时字符串为第一个单词,第二个单词为逗号出现后的字符串。

    if(userInput.charAt(userInput.length()-1) == ',') 处理输入为hello , 或以逗号ENDS 的任何内容时可能出现的异常。

    【讨论】:

    • 无法编译:ch 可能未初始化
    • 对不起,请稍等
    • 使用String.split()
    猜你喜欢
    • 1970-01-01
    • 2019-05-03
    • 2022-09-27
    • 1970-01-01
    • 2017-04-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-27
    相关资源
    最近更新 更多