Java 读取int、double和字符串并忽略标记

Java 读取int、double和字符串并忽略标记,java,java.util.scanner,Java,Java.util.scanner,程序应该将其作为字符串读入,然后将所有的双精度、整数相加,然后将第一个字符串和最后一个字符串相加。因此,该计划应提供 12.9 ; I @ 13 jav 3.8 ; can @ 6 aru 4.0 ; read @ 109 les 这就是我到目前为止所拥有的,我知道我必须使用scanner跳过令牌 Double total : 20.7 Integer total : 128 Line : I can read Word: javarules 这相当难看,但它会起作用 public

程序应该将其作为字符串读入,然后将所有的双精度、整数相加,然后将第一个字符串和最后一个字符串相加。因此,该计划应提供

12.9 ; I @ 13 jav

3.8 ; can @ 6 aru

4.0 ; read @ 109 les
这就是我到目前为止所拥有的,我知道我必须使用scanner跳过令牌

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);
    }
}

您可以创建一个包含双精度整数的arraylist,然后为第一组字符串创建一个sb生成器,为第二组字符串创建一个stringBuilder

Integer value: 131
Double value: 20.7
Words: javarules
Line: I can read 
String line=“12.9;I@13 jav”;
字符串str[]=line.split(“[;\\@\\s+]”);
StringBuilder sb=新的StringBuilder();
StringBuilder sb2=新的StringBuilder();
ArrayList doubleArray=新的ArrayList();
ArrayList intArray=新的ArrayList();
对于(int i=0;i

您可以将所有内容都放在一个循环中,这样就不必重写所有内容。添加完所有内容后,您可以使用stringBuilder构建一个字符串,并使用arrayList中的数组添加所有内容

那么,您的问题是什么?询问如何完成此操作,因为我被卡住了,无法进一步了解它
Integer value: 131
Double value: 20.7
Words: javarules
Line: I can read 
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]);
    } 
}