Ok so I'm trying to extract 2 different doubles from a string created by this
line=JOptionPane.showInputDialog("Enter infos in this format name:hours@cashperhour");
Name is a String, hours is a Double and cashperhour is a Double too
I sucessfully extracted the string by doing this
name=line.substring(0,line.indexOf(":"));
System.out.print(name);
But it fails with the double
hours=Double.parseDouble(line.substring(line.indexOf(":", line.indexOf("@"))));
System.out.print(hours);
If try it with for example Robert James:34@45 I get
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: -1
at java.lang.String.substring(Unknown Source)
And if I try without the "@" Robert James:34 I get
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)
Can someone help me ? Sorry if it's not written correctly it's my first post here
You could use split(...)
since the values are delimited by :
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]);
Tested and working
Try this:
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]);
Also, for the double Test:
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]);
This compiles for me:
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]);
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.