DAO在加载时将整数初始化为0

时间:2015-11-18 23:35:49

标签: java netbeans dao

当我的系统加载已包含数据的文本文件时,它总是将restaurantTables和restaurantSeats的整数初始化为0?如何阻止这种情况发生并在添加到系统时保留指定的数字?

以下是将其更改回0的代码:

公共类TextRestaurantDAO扩展了RestaurantDAO {         static final char DELIMITER =':';

@Override
public List<Restaurant> loadRestaurants(Path path) {
    List<Restaurant> restaurants = new ArrayList<>();   
    try (Scanner s = new Scanner(new BufferedReader(new FileReader(path.toString())))) {         
        s.useDelimiter(Character.toString(DELIMITER));
        Restaurant r;
        int restaurantId, restaurantTables, restaurantSeats;
        String restaurantName, restaurantLocation;


        while (s.hasNext()) {
            if (s.hasNextInt()) {
                restaurantId = s.nextInt();
            }
            else {
                restaurantId = 0;
            }

           if (s.hasNextInt()) {
                restaurantTables = s.nextInt();

            }
                else {
                    restaurantTables = 0;
            }
           if (s.hasNextInt()) {
                restaurantSeats = s.nextInt();

            }
                else {
                    restaurantSeats = 0;
            }

            restaurantName = s.next();
            restaurantLocation = s.next();
            s.nextLine();
            r = new Restaurant(restaurantId, restaurantName, restaurantLocation, restaurantTables, restaurantSeats);
            restaurants.add(r);
        }
        s.close();
    } catch (FileNotFoundException ex) {
        Logger.getLogger(TextCustomerDAO.class.getName()).log(Level.SEVERE, null, ex);
    }        
    return restaurants;
}


@Override
public void storeRestaurants(Path path, List<Restaurant> restaurants) {
    try (PrintWriter output = new PrintWriter(path.toFile())) {
        for (Restaurant r:restaurants) {
            output.println(toFileString(r));
        }
        output.close();
    } catch (FileNotFoundException ex) {
        Logger.getLogger(TextRestaurantDAO.class.getName()).log(Level.SEVERE, null, ex);
    }        
}

public String toFileString(Restaurant r) {
    return  Integer.toString(r.getRestaurantId()) + DELIMITER +
            r.getRestaurantName() + DELIMITER +
            r.getRestaurantLocation() + DELIMITER +
            r.getRestaurantTables() + DELIMITER +
            r.getRestaurantSeats() + DELIMITER;
}    

}

如果你能提供帮助,我们将不胜感激。

以下是文本文件加载前的示例: 1:里瓦:博思韦尔:31:78:

加载后: 1:里瓦:博思韦尔:0:0:

如何阻止这种情况发生?

三江源

如果您需要更多代码,请询问

0 个答案:

没有答案