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

标签 java java.util.scanner

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/

相关文章:

java - 在android中的硬件后退按钮上关闭应用程序

java - 使用特定的 ClassLoader 获取 CtClass

java - 在java中合并两个图像

java - 扫描仪在使用 next() 或 nextFoo() 后跳过 nextLine()?

java - 处理控制台输入(换行)

java - 无法证明 -100000000000000 适合作为长输入

java - 使用html标签遍历NodeTree

java - 如何以编程方式确定我们在桌面上而不是在应用程序服务器上(显示弹出窗口)?

java - 如何在我的扫描器之前调用 GUI 代码?

java - 使用扫描仪输入和正/负数的“while”无限循环