Reputation: 25
In my program, I need to extract numbers from a String the given string is the following.
String numberOfHours = "12.0 8.0 7.0 7.0 10.0 8.0 0.0 2.0";
I need to extract each value into an array. When I use the split method from the String class I get a null value and also I don't get all the numbers in the array. Here's the code.
String pieces[] = numberOfHours.split(" ");
for(int i = 0 ; i < hoursPerDay.length ; i++){
System.out.println(pieces[i]);
}
Thanks in advance!
Upvotes: 1
Views: 569
Reputation: 8724
public static void main(String[] args){
String numberOfHours = "12.0 8.0 7.0 7.0 10.0 8.0 0.0 2.0";
String pieces[] = numberOfHours.split("\\s+");
int num[] = new int[pieces.length];
for(int i = 0; i < pieces.length; i++){
//must cast to double here because of the way you formatted the numbers
num[i] = (int)Double.parseDouble(pieces[i]);
}
for(int i = 0; i < num.length; i++){
System.out.println(num[i]);
}
}
Upvotes: 0
Reputation: 909
This:
String numberOfHours = "12.0 8.0 7.0 7.0 10.0 8.0 0.0 2.0";
String pieces[] = numberOfHours.split("\\s+");
System.out.println(pieces.length);
prints: "8". Is it what you're looking for?
Upvotes: 4