-2

This is the set of doubles and ints that I parsed is named gradeList, and will be parsed to a constructor. The grade List is: "5 - 90 85 95.5 77.5 88" The '5' is an int but everything else should be a double. I parsed it like so

public Grades(String gradeList)
{
    Double.parseDouble(gradeList);
    grades = new Grade[5];
}

I don´t know how to take in the '5' as the length of an array and the other 5 doubles be the data inside of the new array.

Razonixx
  • 15
  • 2

2 Answers2

0

Tokenize (split) on whitespace. Grab the first item as the array size and convert the rest.

This stackoverflow page shows how to split on whitespace How do I split a string with any whitespace chars as delimiters?

Community
  • 1
  • 1
L. Blanc
  • 2,150
  • 2
  • 21
  • 31
  • and what about the "-"? – Alexander Mar 19 '15 at 23:58
  • But how do I take just the first item? – Razonixx Mar 19 '15 at 23:58
  • You can parse on '-' and whitespace. Using guava (which is awesome). Iterable x = Splitter.on(CharMatcher.anyOf("- ")).split(str); will work for - and a space. Splitter returns an iterable, so the first time you call next(), it will give you the first element. – L. Blanc Mar 20 '15 at 00:00
0

A simple way could be:

String gradeList = "5 - 90 85 95.5 77.5 88";
String gradeArray [] = gradeList.split(" ");
int firstElement = Integer.parseInt(gradeArray[0]);
double gradeDoubleArray [] = new double[firstElement];
for(int i = 2; i < firstElement + 2; i++){
    gradeDoubleArray[i-2] = Double.parseDouble(gradeArray[i]);
}
Walter
  • 279
  • 3
  • 5