好的,我试图从这个
创建的字符串中提取2个不同的双打 line=JOptionPane.showInputDialog("Enter infos in this format name:hours@cashperhour");
名称是一个字符串,小时是双倍,而cashperhour是双倍
我通过这样做成功地提取了字符串
name=line.substring(0,line.indexOf(":"));
System.out.print(name);
但它失败了双
hours=Double.parseDouble(line.substring(line.indexOf(":", line.indexOf("@"))));
System.out.print(hours);
如果试试罗伯特詹姆斯:34 @ 45我得到
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: -1
at java.lang.String.substring(Unknown Source)
如果我尝试没有" @"罗伯特詹姆斯: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)
有人能帮助我吗?对不起,如果没有正确写入,这是我在这里的第一篇文章
答案 0 :(得分:0)
您可以使用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]);
答案 1 :(得分:0)
经过测试和运作
试试这个:
String data = "Enter infos in this format name:hours@cashperhour";
String[] split_data = data.split(":",2);
String[] between = split_data[1].split("@",2);
//Your doubles:
System.out.println(between[0]);
System.out.println(between[1]);
另外,对于双重测试:
String data = "Enter infos in this format name:1.2@5.4";
String[] split_data = data.split(":",2);
String[] between = split_data[1].split("@",2);
//Your doubles:
System.out.println(between[0]);
System.out.println(between[1]);
double hours = Double.parseDouble(between[0]);
double cashperhour = Double.parseDouble(between[1]);
这为我编译:
public class Test {
/**
* @param args
*/
public static void main(String[] args) {
String data = "Enter infos in this format name:1.2@5.4";
String[] split_data = data.split(":",2);
String[] between = split_data[1].split("@",2);
//Your doubles:
System.out.println(between[0]);
System.out.println(between[1]);
double hours = Double.parseDouble(between[0]);
double cashperhour = Double.parseDouble(between[1]);
}
}