使用字符串和浮点数读取文件并将它们分配给数组

时间:2017-10-22 03:41:24

标签: java arrays

我想设计一个可以读取如下文件的代码:

杰克12.00 13.24 6

Sarah 11.23 24.01 8

Alex 10.65 19.45 4

我需要为Strings,第一个float,第二个float和int创建单独的数组。 我该怎么做呢?

这是我到目前为止:我不知道如何为两个浮点数制作单独的数组。我还不断获得exception IndexOutOfBoundsException: 0 at EmployeePay.main..

import java.util.Scanner;
import java.io.*;
 public class EmployeePay {
   public static void main(String[] args) throws FileNotFoundException  {
    if (args.length != 1) {  
        final String msg = "Usage: EmployeePay name_of_input file";
          System.err.println(msg);
            throw new IllegalArgumentException(msg);
           }

      final String inputFileName = args[0];
      final File input = new File (inputFileName); 
      final Scanner scanner = new Scanner(new BufferedReader(new FileReader(input)));
              String Id = "Employee Id:";
              String Hours = "Hours worked:";
              String WageRate = "Wage Rate:";
              String Deductions = "Deductions:";
              System.out.printf("%s %-10s %-20s %-30s", Id, Hours, WageRate, Deductions);

              int lineNumber = 0;
           while (scanner.hasNextLine()){
            lineNumber =lineNumber +1;
            String [] Identification= new String [lineNumber-1];
            int [] TotalDeductions = new int [lineNumber-1];
            float [] WorkTime = new float[lineNumber-1];    
                if(scanner.hasNextInt()){
                    TotalDeductions[lineNumber-1] = scanner.nextInt();
                    System.out.println(TotalDeductions[lineNumber-1]);

            }
              else if (scanner.hasNextFloat()){
                WorkTime[lineNumber-1]= scanner.nextFloat();


              }
               else {
                Identification[lineNumber-1] = scanner.next();
                System.out.println(Identification[lineNumber-1]);
               }


           }

       }
   }        

3 个答案:

答案 0 :(得分:0)

我假设您的String值不包含空格。这是一种伪代码,请尝试自己并探索每一行为什么这样做:

String s[] = new String[size];
float f1[] = new float[size];
float f2[] = new float[size];
for(int i=0; i<numberOfLines;i++) {
    String x = "Jake 12.00 13.24 6";

    String[] arr = x.split(" ");
    s[i] = arr[0];
    f1[i] = Float.valueOf(arr[1]);
    f2[i] = Float.valueOf(arr[2]);
}

答案 1 :(得分:0)

由于此声明exception IndexOutOfBoundsException: 0 at EmployeePay.main.,发生此错误if (args.length != 1)。 它应该是if(args.length!=0) 如果在命令提示符下没有传递参数,则args.length为0.因此,此语句将抛出异常final String inputFileName = args[0]; 因此,您需要检查args.length

答案 2 :(得分:0)

如果您的数据文件确实与您在帖子中显示的数据行之间有空行,那么您在阅读文件和处理获得的信息时也需要处理这些文件。你显然想跳过这些特定的行。如果情况并非如此,那么它只会向您展示在此处提问时提供完整准确信息的重要性。这里没有人想要真正承担任何责任。

创建数组时,最好先了解一个数组需要多大的数据,这样才能正确地将其初始化为所需的大小。这是List或ArrayList更好的地方,您可以在需要时添加它们。从此,要正确初始化所有不同的数组(String [],float [],float []和int []),您需要知道数据文件中包含多少有效数据行。有效数据线是指实际包含数据的行,而不是空行。因此,第一个自然步骤是计算这些线。获得计数后,您可以将所有数组初始化为该行数。

现在您需要做的就是逐行重新读取文件数据,拆分每一行以获取数据段,然后将每个数字段转换为其各自的Array数据类型。一旦从文件中填充了所有数组,就可以使用这些数组中包含的数据执行任何操作。执行此任务的代码可能如下所示:

String inputFileName = "MyDataFile.txt";
Scanner scanner;
int linesCount = 0;
try {
    // Count the total number of valid data lines
    // within the file (blank line are skipped).
    scanner = new Scanner(new File(inputFileName));
    while (scanner.hasNextLine()) {
        String strg = scanner.nextLine().trim();
        if (!strg.equals("")) { linesCount++; }
    }

    // Declare our different Arrays and size them to
    // the valid number of data lines in file.
    String[] employeeID = new String[linesCount];
    float[] hours = new float[linesCount];
    float[] wageRate = new float[linesCount];
    int[] deductions = new int[linesCount];

    // Read through the file again and place the data 
    // into their respective arrays.
    scanner = new Scanner(new File(inputFileName));
    int counter = 0;
    while (scanner.hasNextLine()){
        // Get the next line in file...
        String strg = scanner.nextLine().trim();
        // If the file line is blank then skip it.
        if (strg.equals("")) { continue; }
        // otherwise split the line by its space
        // delimiter ("\\s+" takes care of 1 OR more
        // spaces just in case).
        String[] values = strg.split("\\s+");
        // Add to the employeeID string array.
        employeeID[counter] = values[0];
        // Control what is placed into the elements of each 
        // float or integer array. If there is no value data 
        // supplied in file for the employee Name then make 
        // sure 0.0 (for floats) or 0 (for integers) is placed 
        // there after all, you can't parse a null string ("").
        if (values.length >= 2) { hours[counter] = Float.parseFloat(values[1]); }
        else { hours[counter] = 0.0f; }
        if (values.length >= 3) { wageRate[counter] = Float.parseFloat(values[2]); }
        else { wageRate[counter] = 0.0f; }               
        if (values.length == 4) { deductions[counter] = Integer.parseInt(values[3]); }
        else { deductions[counter] = 0; }
        counter++;
    }
    scanner.close();

    // Now that you have all your arrays you can
    // do whatever you like with the data contained
    // within them:
    String Id = "Employee Id:";
    String Hours = "Hours worked:";
    String WageRate = "Wage Rate:";
    String Deductions = "Deductions:";
    System.out.printf("%-15s %-15s %-15s %-15s%n", Id, Hours, WageRate, Deductions);
    for (int i = 0; i < employeeID.length; i++) {
        System.out.printf("%-15s %-15s %-15s %-15s%n", employeeID[i], hours[i], wageRate[i], deductions[i]);
    }
} 
catch (FileNotFoundException ex) { ex.printStackTrace(); }