【问题标题】:Need help splitting input from a String into int需要帮助将输入从 String 拆分为 int
【发布时间】:2013-04-12 02:10:19
【问题描述】:

我让用户以这种格式(4/8–3/12 或 3+2/3 或 12/16*4 或 -2/3/64/96)输入分数问题,并且需要拆分将两个分数放入一个数组中,然后我需要拉出两者的分子和分母,这样我就可以在我的另一个文件中简化它们并进行它要求的任何计算,所以我需要使用一个数组,这样我就可以调用具有符号的元素在里面。

System.out.println("Enter Fraction:");
String answer = s.nextLine(); 


String[] numbers = answer.split(" ");
System.out.print(numbers);

有没有办法将数组拆分为 int 变量?我搞不清楚了。解决方案可能很简单,但现在已经在这个项目中待了 7 个小时左右。

【问题讨论】:

    标签: java string split int


    【解决方案1】:

    您可以使用简单的正则表达式拆分输入,如下所示:

    Pattern p = Pattern.compile("\\d+|[+-/*]");
    String inp = "2/3/64/96";
    Matcher m = p.matcher(inp);
    while (m.find()) {
        System.out.println(m.group());
    }
    

    这个解决方案的核心是一个正则表达式:

    \\d+|[+-/*]
    

    \\d+ 表示“一个或多个数字;[+-/*] 表示“+、-、/ 或 * 中的任何一个”。

    这是demo on ideone。

    请注意,您的程序需要非常小心地确定 + 或 - 是一元“更改符号”还是二元运算:当符号位于开头或紧跟在另一个运算符之后时,它是一元的;否则,它是二进制的。

    【讨论】:

      【解决方案2】:

      Eric Lippert 在处理这些问题时给出了我所见过的最好的建议。

      用英文/伪代码写出问题,然后开始将伪代码更改为真实代码。

      Get Answer from user
      Break Answer up to the 2 fractions/numbers and the math operator
      Take the 2 different fractions and convert them to a double, float, whatever you need
      Apply the math operation to the 2 numbers from the above step
      Output the answer
      

      现在只需开始用您将如何执行此操作替换每一行。我相信您可能可以弄清楚每一步,但有时我们在考虑整个问题时会迷失方向。如果您无法确定单个步骤,请发布您尝试过的代码,我们可以帮助解决特定问题。

      【讨论】:

      • 我宁愿不将它们转换为双精度或浮点数,因为我发现分数可以采用分数和答案的最低形式。
      • 因此我添加了“随便你”的部分,double/float 只是一个建议。
      【解决方案3】:

      到目前为止,您的代码只是将输入拆分为表达式。您仍然需要将表达式拆分为分数。

      当你已经有分数的字符串数组时,你可以将每个元素分成 2 个整数:

      1. 使用split("/")将其拆分为子字符串

      2. 使用Integer.parseInt() 方法将每个子字符串转换为int。

      【讨论】:

        猜你喜欢
        • 2016-04-12
        • 1970-01-01
        • 2022-07-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-02-07
        • 1970-01-01
        相关资源
        最近更新 更多