【问题标题】:How to create a String array from an input.txt file如何从 input.txt 文件创建字符串数组
【发布时间】:2016-01-02 16:19:45
【问题描述】:

我在创建从命令行读取为参数的数组时遇到问题。该文件的第一行是一个整数 N,该文件的其余部分在每一行都包含字符串。第一个整数是数组的大小。我已经成功分配了数组,但是我无法让它读取 input.txt 文件的整行。

以下是 input.txt 文件的示例:

4
hey, 03982
bye, 30980324
no, 3290823
yes, 30948432

这是我的代码截图:

import java.util.Scanner;
import java.io.*;
import java.util.Arrays;

class databaseSearch{

public static void main( String[] args ){

    Scanner sc = null;

    // if no arguments are entered, print out 
    // error message and correct way to invoke program
    if(args.length == 0){
            errorMessage();
    }

// Try and open the first argument on the command line
    try{
        sc = new Scanner(new File(args[0]));
    }catch(FileNotFoundException e){
        System.err.println(e.getMessage());
        errorMessage();
    }


int arraySize = sc.nextInt();
sc.nextLine();
String[] DB = new String[arraySize];
for( int i = 0; i < arraySize; i++ ){
    DB[i] = sc.nextLine();
}



    System.out.println(Arrays.toString(DB));

}

// errorMessage()
// prints out an error message with correct with to invoke program
// terminates after instructions are given
static void errorMessage(){
    System.err.println("Please try again by running the program along with a correct file.");
    System.exit(1);
}
}

【问题讨论】:

  • 什么是业务变量?此示例无法验证,请尝试在调试器中运行它以逐步查看结果。什么是正确的?
  • 修好了,应该是DB.length

标签: java arrays java.util.scanner stdin


【解决方案1】:

使用Files.readAllLines().

List<String> lines = Files.readAllLines(Paths.get(arg[0]));
if (lines.isEmpty())
  throw new IllegalArgumentException("Empty file");
int count = Integer.parseInt(lines.remove(0)); 
if (lines.size() != count)
  throw new IllegalArgumentException("Incomplete file");
String[] db = lines.toArray(new String[count]);

【讨论】:

    【解决方案2】:

    由于您知道文件的结构,因此您的外部 while 循环看起来不必要且危险。取而代之的是获取您的扫描仪,从文件中获取第一个 int,使用该 int 创建您的数组,然后循环该数字次,就是这样。

    伪代码

    get scanner for file
    read in first int, call it arraySize. Note that nextInt() does not get the end of line token
    get nextLine from scanner **and discard it** to handle the end of line token
    create a String array arraySize length.
    for int i goes from 0 to less than arraySize
       get a line from the Scanner
       put line in your String array
       //  Split the line using String split. // not sure if this needs to be done
    end for loop
    close scanner
    

    旁注:您需要学习和使用 Java 命名约定,包括以小写字母开头的变量和方法名称,以及以大写字母开头的类名称。遵循这些规则将允许您创建其他人(我们!)可以更轻松地遵循的代码。

    例如,

    public static void main(String[] args) {
        if (args.length == 0) {
            // !! exit/error
        }
    
        String filePath = args[0];
        String[] lines = null;
    
        // use try with resources so that the resource, here the Scanner
        // gets closed when done being used.
        try (Scanner scan = new Scanner(new File(filePath))) {
            int arraySize = scan.nextInt();  // get first int
            scan.nextLine();  // swallow the end-of-line token
            lines = new String[arraySize];
            for (int i = 0; i < lines.length; i++) {
                lines[i] = scan.nextLine();
            }
    
            System.out.println("Display results:");
            for (String line : lines) {
                System.out.println(line);
            }
        } catch (FileNotFoundException e1) {
            e1.printStackTrace();
        }
    }
    

    【讨论】:

    • 所以我所做的是我将数组设为全局变量,因此它可以从程序中的任何位置运行,循环运行良好,只是没有用我需要填充的内容填充我的数组它与。如果我将 nextLine() 更改为 Next(),它将获取第二行的第一个标记并仅用该标记填充整个数组
    • @sartar:试试我上面的建议。此外,我们不了解全局/本地,因为这不是您与我们共享的信息。如果这是我的程序,并且如果我在方法中读取数组,我会将数组设为 local 变量并让我的读取方法 return 完成数组。
    • 我猜所以我真的不需要我的 while 循环和前几行中的 if 语句?我只是认为即使最初打开和阅读 .txt 文件也是必要的。
    • @sartar:为了什么?每当您需要重复某些内容时,都会使用 while 循环,但您事先不知道需要重复多少次。这在哪里发挥作用?读取第一个整数后,您就知道要循环多少次。
    • 好的,我现在就试试你的伪代码。另外,在.txt文件中,由于第一个数字是整数,其余都是字符串,编译器是否将整数读取为字符串,需要对其进行解析???或者它会将整数和字符串识别为不同的东西
    【解决方案3】:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-20
      • 2020-04-16
      • 2012-02-18
      相关资源
      最近更新 更多