12.9 ; I @ 13 jav
3.8 ; can @ 6 aru
4.0 ; read @ 109 les
该程序应该以字符串形式读取它,然后添加所有的双精度数,整数,然后将第一个字符串和最后一个字符串一起添加。所以程序应该提供
Double total : 20.7
Integer total : 128
Line : I can read
Word: javarules
这是我到目前为止所知道的,我知道我必须使用扫描仪来跳过令牌。
public class Test {
public static void main (String args[]) throws FileNotFoundException {
Scanner sc = new Scanner(Test4.class.getResourceAsStream("week2inputdata.txt"));
double doubletotal = 0;
int inttotal = 0;
String line = " ";
String word;
Scanner scanLine;
while (sc.hasNextLine()){
scanLine = new Scanner (sc.nextLine());
scanLine.next();
line += sc.hasNextLine();
inttotal += sc.nextInt();
// scanLine = new Scanner (sc.nextLine());
// scanLine.next();
// line += sc.next() + " ";
// inttotal += sc.nextInt();
doubletotal += sc.nextDouble();
}
System.out.println(inttotal);
System.out.println(doubletotal);
System.out.println(line);
}
}
答案 0 :(得分:3)
这是相当丑陋但它会起作用,
String[] weirdLookingString = new String[] { "12.9 ; I @ 11 jav", "3.8 ; can @ 11 aru"
,"4.0 ; read @ 109 les" };
double doubleValue = 0.0;
String strValue1 = "";
String strValue2 = "";
int integerValue = 0;
for (int i = 0; i < weirdLookingString.length; i++) {
String array[] = weirdLookingString[i].split("[;\\@]\\s+");
String lastString[] = array[2].split("\\s");
integerValue += Integer.parseInt(lastString[0]);
doubleValue += Double.parseDouble(array[0]);
strValue2 += lastString[1];
strValue1 += array[1];
}
System.out.println("Integer value: " + integerValue);
System.out.println("Double value: " + doubleValue);
System.out.println("Words: " + strValue2);
System.out.println("Line: " + strValue1);
<强>输出强>,
Integer value: 131
Double value: 20.7
Words: javarules
Line: I can read
答案 1 :(得分:0)
您可以创建double,Integers的arraylist,然后为第一组字符串创建一个sb构建器,为第二组字符串创建一个stringBuilder。
String line = "12.9 ; I @ 13 jav";
String str[] = line.split("[;\\@\\s+]");
StringBuilder sb = new StringBuilder();
StringBuilder sb2 = new StringBuilder();
ArrayList<Double> doubleArray = new ArrayList();
ArrayList<Integer> intArray = new ArrayList();
for(int i =0; i < str.length; i++){
if(i == 0){
doubleArray.add(Double.parseDouble(str[i]));//convert to double and add it to the list
}else if(i == 1){
sb.append(str[i]);
}else if(i == 2){
doubleInt.add(Integer.parseInt(str[i]));//convert it to integer and add to the list
}else if(i == 3){
sb2.append(str[i]);
}
}
你可以把所有东西放在一个循环中,这样你就不必重写所有内容。添加完所有内容后,您可以使用stringBuilder构建一个字符串,并使用arrayList
中的数组添加所有内容