需要帮助将输入从String拆分为int

时间:2013-04-12 02:10:20

标签: java string split int

我让用户输入这种格式的分数问题(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个小时左右。

3 个答案:

答案 0 :(得分: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

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

答案 1 :(得分:0)

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

现在开始用你将如何做到这一点来替换每一行。我有信心你可以找出每一步,但有时我们会在整体思考问题时迷失方向。如果您无法找出单个步骤,请发布您尝试过的代码,我们可以帮助解决特定问题。

答案 2 :(得分:0)

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

如果已经有分数的String数组,则可以将每个元素拆分为2个整数:

  1. 使用split("/")

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

相关问题