在Java中从字符串中解析int、double和String

3

我需要在Java课程中完成一项任务,使用Scanner方法输入一个整数(物品数量),一个字符串(物品名称)和一个浮点数(物品成本)。我们必须使用Scanner.nextLine()方法并从那里进行解析。

示例:

System.out.println("Please enter grocery item (# Item COST)");
String input = kb.nextLine();         

用户会输入类似这样的内容:3 Captain Crunch 3.5 输出结果应该是:Captain Crunch #3 for $10.5 我遇到的问题是如何从字符串中解析出整数和浮点数,同时还要保留字符串值。
3个回答

3
  1. 首先,将字符串分割并获得一个数组。
  2. 循环遍历该数组。
  3. 然后,您可以尝试将数组中的字符串解析为其相应的类型。

例如: 在每次迭代中,检查它是否是整数。以下示例检查第一个元素是否为整数。

string[0].matches("\\d+")

或者你可以使用以下的try-catch(不推荐)
try{
   int anInteger = Integer.parseInt(string[0]);
   }catch(NumberFormatException e){

   }

2
为什么要循环?你已经知道它应该包含3个元素。 - Tom
@Tom 以防万一 :-) 更容易编程,可能会这样。 - Nabin
谢谢你的帮助! :) 我以前从未使用过stackoverflow,但它已经证明非常有用了。 - Stephen L'Allier
好的,我会的。再次感谢。 - Stephen L'Allier

2

如果我理解你的问题,你可以使用String.indexOf(int)String.lastIndexOf(int)方法,例如:

String input = "3 Captain Crunch 3.5";
int fi = input.indexOf(' ');
int li = input.lastIndexOf(' ');
int itemNumber = Integer.parseInt(input.substring(0, fi));
double price = Double.parseDouble(input.substring(li + 1));
System.out.printf("%s #%d for $%.2f%n", input.substring(fi + 1, li),
            itemNumber, itemNumber * price);

输出结果为

Captain Crunch #3 for $10.50

看起来像是“一次性购买3个只要一个的价格”:)。 - Tom
@Tom 已修复,但这是一次性的价格。 - Elliott Frisch

0
    Scanner sc = new Scanner(System.in);
    String message = sc.nextLine();//take the message from the command line
    String temp [] = message.split(" ");// assign to a temp array value
    int number = Integer.parseInt(temp[0]);// take the first value from the message
    String name = temp[1]; // second one is name.
    Double price = Double.parseDouble(temp[2]); // third one is price
    System.out.println(name +  " #" + number + " for $ "  + number*price ) ;

这似乎非常有用,我唯一的问题是如果名字超过一个单词怎么办?例如,“Captain Crunch”或类似的名称? - Stephen L'Allier

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接