试图阻止循环无限循环,但也要防止它在每次运行中“中断”

时间:2011-12-07 09:33:53

标签: java arrays object

我有一个循环,它在程序启动时读取文本文件中的行数,然后根据行数将所有对象存储到一个新的(Vehicle [])数组中(最多4个)。

public boolean addVehicle(Vehicle[] Honda) throws FileNotFoundException
{
    Scanner reader = new Scanner(file);
    String strLine = "";

        if(canAddVehicle() == true)
        {

        for(int i = 0; i < vehicles.length;i++)
        {
            System.out.println("This file is: " + file);
            int counter = 0;

            if(vehicles[i] == null)
            {
                try{
                    // Open the file that is the first 
                    // command line parameter
                    FileInputStream fstream = new FileInputStream(this.file);

                    // Get the object of DataInputStream
                    DataInputStream in = new DataInputStream(fstream);
                        BufferedReader br = new BufferedReader(new InputStreamReader(in));

                    //Read File Line By Line
                    while ((strLine = br.readLine()) != null)   {

                        //Declare objects inside the array.
                        Honda[counter] = new Vehicle();
                        Honda[counter].readRecord(reader);
                        vehicles[counter] = Honda[counter];
                        counter++;

                    }
                    strLine = "";

                    //Close the input stream and scanner
                    reader.close();
                    in.close();
                    }catch (Exception e){//Catch exception if any
                      System.err.println("Error: " + e.getMessage());
                    }
                  }
                break;
            }
        }
            return true;
        }

我遇到麻烦的部分是这一行:

if(vehicles[i] == null)

程序启动后,用户可以选择将新车辆添加到阵列中。如果你逐行浏览代码,你可以看到它从i = 0开始,让我们说当程序第一次运行它时发现了2行值,所以它将2个对象存储到数组中。 取值0和1。这意味着当用户添加新的Vehicle时,它将跳过if(vehicles[i] == null),因为spot [0]不为null,它包含程序开头的值。

然后导致break;并将你踢出方法而不返回for循环来检查数组中是否还有其他空值。 我可以在这做什么?

6 个答案:

答案 0 :(得分:1)

有两件事, 一个。切换中断以继续,并将中断放在您想要的正确位置。

湾你应该关闭你的文件流,如果你完成使用它,因为当你打开一个fStream它 “保持文件打开”并且在关闭fStream

之前无法使用

答案 1 :(得分:1)

如果您对来源进行格式设置,则可以更轻松地查看您的中断位置。然后尝试考虑如何手动单步执行程序。这通常对我有帮助。您可以决定是否要在循环中打破,或者仅在您刚装载新车时。

Peter Lawrey在使用调试器(在大多数IDE中非常容易)的情况下,在计算出你的程序要执行的操作之后给出了一个很好的评论,你可以通过程序来执行查看每个操作,并在每个步骤检查变量的值。

答案 2 :(得分:1)

你的代码真的没什么意义。根据我对您的问题描述的理解,下面的代码可能或可能不是您想要做的:

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;

public class VehicleList {

    public class Vehicle {
        private final String brand;
        private final String make;
        private final String year;

        public Vehicle(String[] args) {
            if (args.length < 3) {
                throw new IllegalArgumentException("Too few args: " + args.length);
            }
            this.brand = args[0];
            this.make = args[1];
            this.year = args[2];
        }

        @Override
        public String toString() {
            return String.format("%s %s %s", year, brand, make);
        }
    }

    public List<Vehicle> readVehicles(String fileName) throws IOException {
        List<Vehicle> vehicles = new ArrayList<Vehicle>();
        System.out.println(String.format("Reading vehicles from %s:", fileName));
        readVehicles(vehicles, new Scanner(new File(fileName)), false);
        System.out.println(String.format("Reading vehicles from user:"));
        readVehicles(vehicles, new Scanner(System.in), true);
        return vehicles;
    }

    private void readVehicles(List<Vehicle> vehicles, Scanner scanner, boolean skipLineCheck) {
        int count = 0;
        while (skipLineCheck || scanner.hasNextLine()) {
            String[] tokens = scanner.nextLine().split("\\s+");
            if (tokens.length < 3) {
                break;
            }
            vehicles.add(new Vehicle(tokens));
            count++;
        }
        scanner.close();
        System.out.println(String.format("Read %s vehicles", count));
    }

    public static void main(String[] args) throws IOException {
        VehicleList instance = new VehicleList();
        List<Vehicle> vehicles = instance.readVehicles("vehicles.txt");
        System.out.println("Read the following vehicles:");
        System.out.println(Arrays.toString(vehicles.toArray()));
    }
}

需要布尔值skipLineCheck来阻止扫描程序读取文件中的最后一行并抛出NoSuchElementException。对于用户输入,我们不想进行此检查,因为它会强制用户提供额外的RETURN来结束输入。

要运行此操作,您需要在工作目录中创建一个名为“vehicles.txt”的文件,例如以下内容:

Volvo Station 2008
Audi A4 2009
Honda Civic 2009
Toyota Prius 2008

测试运行提供如下输出:

Reading vehicles from vehicles.txt
Read 4 vehicles
Reading vehicles from user
Nissan Micra 2002
BMW cabriolet 1996

Read 2 vehicles
Read the following vehicles: 
[2008 Volvo Station, 2009 Audi A4, 2009 Honda Civic, 2008 Toyota Prius, 2002 Nissan Micra, 1996 BMW cabriolet]

答案 3 :(得分:0)

为什么你要在那里休息一下 - 它只是让它完全按你所描述的那样做。删除它,一切都会很好。

答案 4 :(得分:0)

基于这一陈述:然后导致休息;并且在没有返回for循环的情况下将你踢出方法,以检查数组中是否还有其他空值。

听起来你想要一个休息的地方。

break会导致for循环中断,而continue会导致循环中的代码被读取(从上到下),i递增1(在这种情况下)

答案 5 :(得分:0)

感谢大家的答案。我编程大约12个小时,当我问这个问题时,我的思绪已经死了。不知道我在做什么。我用这个完成了我的代码:

public boolean addVehicle(Vehicle[] Honda) throws FileNotFoundException
{
    boolean found = false;
    int position = 0;
        if(canAddVehicle() == true)
        {
            for(int i = 0; i < vehicles.length && !found; i++)
            {
                if(vehicles[i] == null)
                {
                    position = i;
                    found = true;
                }
            }

               Scanner reader = new Scanner(file);
               while(reader.hasNext())
               {
                   Honda[position] = new Vehicle();
                   Honda[position].readRecord(reader);
                   vehicles[position] = Honda[position];
                   position++;

               }
                reader.close();
                return true;
        }
        return false;
}