【问题标题】:txt file to array (NO LISTS)txt 文件到数组(没有列表)
【发布时间】:2018-07-28 09:46:35
【问题描述】:

我正在尝试读取一个包含 81 个整数的文件并用这 81 个整数填充一个数组,因此我检查了这些数字的有效性。

public static int[][] ReadIn () {

        Scanner input = new Scanner(System.in);

        System.out.println("Please enter a filename: ");
        int[][] grid = new int[9][9];
        for(int i = 0; i < 9; i++)
            for(int j = 0; j < 9; j++)
                grid[i][j] = input.nextInt();


        File file = new File(input);

        BufferedReader br = new BufferedReader(new FileReader(file));

        String st;
        while((st = br.readLine()) != null)
            System.out.println(st);

        return grid;
    }

我的问题是当我从用户那里读取文件时出现错误

CheckSudokuSolution.java:24: error: no suitable constructor found for File(Scanner)
        File file = new File(input);
                    ^
    constructor File.File(String) is not applicable
      (argument mismatch; Scanner cannot be converted to String)
    constructor File.File(URI) is not applicable
      (argument mismatch; Scanner cannot be converted to URI)
Note: Some messages have been simplified; recompile with -Xdiags:verbose to get full output
1 error

我不确定为什么会发生此错误或如何解决它。

【问题讨论】:

  • 好的,然后没有列表。您需要从Scanner 获取字符串,而不是使用Scanner 本身,例如new File(input.next()).
  • 试试scanner.nextLine()

标签: java arrays java-io


【解决方案1】:
public static int[][] readASolution(String filename) {
        int[][] grid = new int[9][9];

        try {
            Scanner sc = new Scanner(new File(filename));
            int i = 0;

            while(sc.hasNext()) {
                int j = 0;
                String line = sc.nextLine();

                for( int x = 0; x < line.length(); x++) 
                    if( Character.isDigit(line.charAt(x)) ) {
                        grid[i][j] = Character.getNumericValue(line.charAt(x)); 
                        j++;
                    }
                if (i == 9) break;
                i++; 
            }
        } catch(FileNotFoundException e ) { 
            System.err.println( "Error: " + e );
        }
        return grid;
    }

这是我为其他处理此类问题的其他人提出的正确解决方案。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多