简体   繁体   中英

Reading data and storing in array Java

I am writing a program which will allow users to reserve a room in a hotel (University Project). I have got this problem where when I try and read data from the file and store it in an array I receive a NumberFormatException .

I have been stuck on this problem for a while now and cannot figure out where I am going wrong. I've read up on it and apparently its when I try and convert a String to a numeric but I cannot figure out how to fix it.

Any suggestions, please?

This is my code for my reader.

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();

This is the error message在此处输入图像描述

This is the data in my file which I am trying to read:

在此处输入图像描述

Change your while loop like this

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
}

Use next() instead of nextLine() .

You're trying to parse the whole line to Integer. You can read the whole line as a String, call

.split(" ")

on it. This will split the whole line into multiple values and put them into an array. Then you can grab each item from the array and parse separately as you intended.

Please avoid posting screenshots next time, use proper formatting and text so someone can easily copy your code or test data to IDE and reproduce the scenario.

With Scanner one must use hasNextLine, nextLine, hasNext, next, hasNextInt, nextInt etcetera. I would do it as follows:

  • Using Path and Files - the newer more general classes io File.
  • Files can read lines, here I use Files.lines which gives a Stream of lines, a bit like a loop.
  • Try-with-resources: try (AutoCloseable in =...) {... } ensures that in.close() is always called implicitly, even on exception or return.
  • The line is without line ending.
  • The line is split into words separated by one or more spaces.
  • Only lines with at least 6 words are handled.
  • Create a Room from the words.
  • Collect an array of Room-s.

So:

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[]
}

For local variables use camelCase with a small letter in front.

The code uses the default character encoding of the system to convert the bytes in the file to java Unicode String. If you want all Unicode symbols, you might store your list as Unicode UTF-8, and read them as follows:

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

An other issue is the imprecise floating point double . You might use BigDecimal instead; it holds a precision:

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

It is however much more verbose, so you need to look at a couple of examples.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM