是的,给猫剥皮的方法不止一种:
第一:String.split()
String[] parts = inputString.split(','); //split the input
String name = parts[0]; //get first part.
double[] scores = new double[4]; //create array for doubles
for(int i=0; i<4; i++) { //fill array of doubles --> array index checking might be needed!
scores[i]=Double.parseDouble(scores[i+2]);
}
但是,由于这涉及浮点数,您应该阅读每个计算机科学家都应该知道的关于浮点运算的知识,了解为什么他们可以显示有趣的结果......或者,您可以使用 BigDecimals
BigDecimal exactResult = BigDecimal.valueOf(scores[i+2]);
Scanner s = new Scanner(inputString);
s.useDelimiter(",");
String name = s.next();
double[] scores = new double[4]; //create array for doubles
String someCode = s.next();
for(int i=0; i<4; i++) { //fill array of doubles
scores[i]=Double.parseDouble(s.next()); //null check might be needed!
}
第三:使用模式
//this pattern is very ugly (unsacalable, unmaintainable), but should work for now as poc...
Pattern p = Pattern.compile("([^,]*),\\s*([^,]*),\\s*([^,]*),\\s*([^,]*),\\s*([^,]*),\\s*([^,]*)");
Matcher m = p.matcher(inputString);
if(matcher.matches()) {
String name = group(1);
String someCode = group(2);
double[] scores = new double[4]; //create array for doubles
for(int i=0; i<4; i++) { //fill array of doubles
scores[i]=Double.parseDouble(s.group(i+3)); //null check might be needed!
}
}