好吧,我正在尝试从由此创建的字符串中提取 2 个不同的 double
line=JOptionPane.showInputDialog("Enter infos in this format name:hours@cashperhour");
Name 是一个 String,hours 是一个 Double,cashperhour 也是一个 Double
我通过这样做成功提取了字符串
name=line.substring(0,line.indexOf(":"));
System.out.print(name);
但是 double 失败
hours=Double.parseDouble(line.substring(line.indexOf(":", line.indexOf("@"))));
System.out.print(hours);
如果尝试使用例如 Robert James:34@45 我得到
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: -1
at java.lang.String.substring(Unknown Source)
如果我尝试不使用“@”Robert James:34,我会得到
Exception in thread "main" java.lang.NumberFormatException: For input string: ":34"
at sun.misc.FloatingDecimal.readJavaFormatString(Unknown Source)
at sun.misc.FloatingDecimal.parseDouble(Unknown Source)
at java.lang.Double.parseDouble(Unknown Source)
有人可以帮助我吗?抱歉,如果写得不正确,这是我的第一篇文章
最佳答案
您可以使用 split(...)
因为这些值是由 :
分隔的
String[] data = line.split("\\:");
String name = data[0];
String[] numbers = data[1].split("@");
double hours = Double.parseDouble(numbers[0]);
double cashperhour = Double.parseDouble(numbers[1]);
关于java - 从字符串中提取 2 个不同的 double 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26568392/