【问题标题】:Filled/Unfilled Rectangle From File文件中的填充/未填充矩形
【发布时间】:2021-01-23 00:17:43
【问题描述】:

该项目应该读取一个文件,其中文件的第一行说明要制作多少个矩形,其余的是尺寸以及是否填充。假设一个带有 toString 的 Rectangle 类来格式化矩形。在设置变量 numLines 时,我的 while 循环的第一行出现输入不匹配错误,需要一些帮助。

public static void main(String[] args) {
        int columns = 0;
        int rows = 0;
        int numLines = 1;
        String fill;
        boolean filled = false;
        
        //first line of file creates array size
        Rectangle[] rectangle = new Rectangle[numLines];
        Scanner inFile = new Scanner("rectangle.txt");
        
        //reads file 
        while (inFile.hasNext()) {
            numLines = inFile.nextInt();
            for (int i=0; i<numLines; i++) {
                columns = inFile.nextInt();
                rows = inFile.nextInt();
                fill = inFile.nextLine();
                if (fill.equals("filled")) {
                    filled = true;
                }
                Rectangle rec = new Rectangle(rows, columns, filled);
                rectangle = new Rectangle[numLines];
                rectangle[i] = rec;
            }

//example of file being read

    6
    6 3 filled
    3 6 unfilled
    4 4 filled
    6 6 unfilled
    9 4 filled
    4 8 unfilled

【问题讨论】:

    标签: java file while-loop file-io


    【解决方案1】:

    我收到输入不匹配错误

    Scanner inFile = new Scanner("rectangle.txt");
    

    您正在使用文本字符串而不是文件创建扫描程序。文本字符串“rectangle.txt”不是 int 值。

    如果要从 File 中读取,则需要指定 File 作为参数:

    Scanner inFile = new Scanner(new File("rectangle.txt"));
    

    【讨论】:

    猜你喜欢
    • 2019-03-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多