12.9 ; I @ 13 jav
3.8 ; can @ 6 aru
4.0 ; read @ 109 les
程序应该将其作为字符串读入,然后将所有 double 、整数相加,然后将第一个字符串和最后一个字符串相加。所以程序应该提供
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);
}
}
最佳答案
这很丑陋,但它会起作用,
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
关于java - 读取 int、double 和字符串并忽略标记,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28263991/