【问题标题】:Make string array using file line input using methods使用方法使用文件行输入制作字符串数组
【发布时间】:2021-06-26 04:00:59
【问题描述】:

我正在编写一个代码,它逐行读取一个txt文件,并使用一种方法将每一行作为一个字符串存储在一个数组中。

这是txt文件的内容:

04/26/16    Sega 3D Classics Collection
07/14/16    Batman: Arkham Underworld
06/24/16    Tokyo Mirage Sessions #FE

我的代码的问题是调试器给了我无法将文件类型更改为字符串类型的消息。我不确定如何将 txt 文件的内容转换为字符串值。

这是我的代码:

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class Main{
  public static void main (String[]args) throws FileNotFoundException{
    File file = new File("releasedates.txt");

    input(file);

  }

  public static String[]input (String file) throws FileNotFoundException{
    String[]arr = new String[3];
    Scanner sc = new Scanner(file);

    for(int i = 0; i < arr.length; i++){
      arr[i] = sc.nextLine();

    }

    return arr;
    
  }

}

【问题讨论】:

  • 你传递了一个 File 的实例,但你的方法需要一个 String 的实例作为参数,错误信息就在

标签: java arrays string file input


【解决方案1】:
public static void main (String[]args) throws FileNotFoundException{
    File file = new File("releasedates.txt");
    input(file);
  }

这里调用输入法。如您所见,您将 File 类的一个实例作为参数传递。

public static String[]input (String file) throws FileNotFoundException

这是您输入法的签名,它接受 String 的实例,而不是 File 的实例。

由于参数用于实例化 Scanner,并且有一个 Scanner 构造函数采用 File 的实例,因此处理此问题的最佳方法是将方法的签名更改为:

public static String[]input (File file) throws FileNotFoundException

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-08-26
    • 2021-05-31
    • 1970-01-01
    • 2016-08-17
    • 2021-04-09
    • 1970-01-01
    • 2022-11-03
    • 1970-01-01
    相关资源
    最近更新 更多