簡體   English   中英

讀取數據並存入數組 Java

[英]Reading data and storing in array Java

我正在編寫一個程序,允許用戶在酒店預訂房間(大學項目)。 我遇到了這個問題,當我嘗試從文件中讀取數據並將其存儲在一個數組中時,我收到一個NumberFormatException

我已經在這個問題上停留了一段時間,無法弄清楚我哪里出錯了。 我已經閱讀了它,顯然是當我嘗試將字符串轉換為數字時,但我無法弄清楚如何修復它。

請問有什么建議嗎?

這是我的讀者代碼。

FileReader file = new FileReader("rooms.txt");
 Scanner reader = new Scanner(file);
 int index = 0; 
    
while(reader.hasNext()) {
    int RoomNum = Integer.parseInt(reader.nextLine());
    String Type = reader.nextLine();
    double Price = Double.parseDouble(reader.nextLine());
    boolean Balcony = Boolean.parseBoolean(reader.nextLine());
    boolean Lounge = Boolean.parseBoolean(reader.nextLine());
    String Reserved = reader.nextLine();
     rooms[index] = new Room(RoomNum, Type, Price, Balcony, Lounge, Reserved);
     index++;
    }
reader.close();

這是錯誤信息在此處輸入圖像描述

這是我試圖讀取的文件中的數據:

在此處輸入圖像描述

像這樣改變你的while循環

while (reader.hasNextLine())
{ 
    // then split reader.nextLine() data using .split() function
    // and store it in string array
    // after that you can extract data from the array and do whatever you want
}

使用next()而不是nextLine()

您正在嘗試將整行解析為 Integer。 您可以將整行讀取為字符串,調用

。分裂(” ”)

在上面。 這會將整行拆分為多個值並將它們放入一個數組中。 然后,您可以從數組中獲取每個項目並按照您的意圖單獨解析。

下次請避免發布屏幕截圖,使用正確的格式和文本,以便有人可以輕松地將您的代碼或測試數據復制到 IDE 並重現該場景。

對於Scanner ,必須使用hasNextLine, nextLine, hasNext, next, hasNextInt, nextInt等。 我會這樣做:

  • 使用路徑和文件 - 更新更通用的類 io 文件。
  • 文件可以讀取行,這里我使用 Files.lines 給出 Stream 行,有點像循環。
  • Try-with-resources: try (AutoCloseable in =...) {... }確保始終隱式調用in.close() ,即使在異常或返回時也是如此。
  • 該行沒有行尾。
  • 該行被分成由一個或多個空格分隔的單詞。
  • 僅處理至少包含 6 個單詞的行。
  • 從單詞創建一個房間。
  • 收集一組 Room-s。

所以:

Path file = Paths.get("rooms.txt");
try (Stream<String> in = Files.lines(file)) {
    rooms = in                                  // Stream<String>
        .map(line -> line.split(" +"))          // Stream<String[]>
        .filter(words -> words.length >= 6)
        .map(words -> {
            int roomNum = Integer.parseInt(words[0]);
            String type = words[1];
            double price = Double.parseDouble(words[2]);
            boolean balcony = Boolean.parseBoolean(words[3]);
            boolean lounge = Boolean.parseBoolean(words[4]);
            String reserved = words[5];
            return new Room(roomNum, type, price, balcony, lounge, reserved);
        })                                      // Stream<Room>
        .toArray(Room[]::new);                  // Room[]
}

對於局部變量,使用前面帶有小寫字母的 camelCase。

代碼使用系統默認的字符編碼將文件中的字節轉換為java Unicode String。 如果您想要所有 Unicode 符號,您可以將您的列表存儲為 Unicode UTF-8,並閱讀如下:

try (Stream<String> in = Files.lines(file, StandardCharsets.UTF_8)) {

另一個問題是不精確的浮點double 您可以改用BigDecimal 它具有精度:

            BigDecimal price = new BigDecimal(words[2]);

然而,它更加冗長,因此您需要查看幾個示例。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM