1

如何拆分文本文件?

说一个文本文件有这样的行:

杰基尔 23.3 33.3 43.2

卡其色 32.5 54.3 43.2

......

到目前为止,对于我的代码,我有这个:

while(scan.hasNext())
     {

          String line = scan.nextLine(); 
          String[] words = .split(" ");

          for(int i = 1; i < words.length - 1; i++)
              System.out.println(words[i]);

编辑

现在打印出来了,我的目标是将所有数字加在一起,然后创建一个平均值,我坚持这里需要做的事情

编辑整个代码:

import java.util.Scanner;
import java.io.File;
import java.io.IOException;
import java.text.DecimalFormat;

public class TemperaturesWeek2
{
    public static void main( String [] args ) throws IOException
    {
        int count=0;
        double averageTemp;
        int averageAbove;
        double highestAverage;

        File inputFile = new File (
                         "C:/Users/Phillip/Documents/Temp/temperatures.txt .txt");
        Scanner scan = new Scanner(inputFile);

        while(scan.hasNext()) {

            String words = scan.next();

            double num1 = scan.nextDouble();
            double num2 = scan.nextDouble();
            double num3 = scan.nextDouble();
            double num4 = scan.nextDouble();
            double num5 = scan.nextDouble();
            double num6 = scan.nextDouble();
            double num7 = scan.nextDouble();

            double average = (num1 + num2 + num3+ num4+ num5+ num6+ num7) / 7;

            System.out.println(words);
            System.out.println("average is : " + average);
        } 
    }
}
}
4

4 回答 4

2

您首先需要获取字符串。然后你需要拆分/解析它。所以如果你想逐行读取文件,它会是这样的:

while(scan.hasNext())
{
    String line = scan.nextLine(); // "Read" your file (one line at a time).
    System.out.println(line); // Test what you read.
    String[] words = line.split(" "); // Parse what you read.

    for(int i = 1; i < words.length; i++){
        System.out.println(words[i]);
    }
}
于 2013-11-13T00:21:30.973 回答
2

尝试这个

while(scan.hasNext()) {

    String line = scan.nextLine(); 
    String[] words = .split(" ");

    double num1 = Double.parseDouble(words[1]);
    double num2 = Double.parseDouble(words[2]);
    double num3 = Double.parseDouble(words[3]);

    double average = (num1 + num1 + num3) / 3;

    System.out.println(line);
    System.out.println("average is : " + average);
}

编辑:使用 nextDouble()

while(scan.hasNext()) {

    String words = acan.next();

    double num1 = scan.nextDouble();
    double num2 = scan.nextDouble();
    double num3 = scan.nextDouble();

    double average = (num1 + num1 + num3) / 3;

    System.out.println(word);
    System.out.println("average is : " + average);

    scan.nextLine();
    // add another scan.nextLine() if you have line spaces between your lines
    scan.nextLine() // only if necessary
}
于 2013-11-13T01:19:53.423 回答
1

伪代码

解析文本文件的每一行。

检查解析的项目是否为 int 如果 int 将其放入数组中 如果扫描的下一个字符为空,则将数组递增到下一个位置直到空文件

然后是一个简单的 for 循环来添加数组的内容。

于 2013-11-13T00:31:20.353 回答
1

我认为这应该有帮助

Float.parseFloat(String s)
于 2013-11-13T01:06:58.117 回答