-1

Im writing a hotel console program, the problem i have at the moment is to load the saved file back to a String[], when the user presses option to load from file.

The text file includes the guest names saved earlier.

Here is the file data

tom
mo
jo
john
meg
bob
jack
veronica
jessica
angelica

And here is all the code I have

Yes thank you i know arrays are 0 index. for loops are starting from 1 because i want to have Room1 instead Room0 as first

THANK YOU PROBLEM SOLVED

public class FileLoad {
    public String[] readLines(String filename) throws IOException {  
        FileReader fileReader = new FileReader(filename);  

        BufferedReader bufferedReader = new BufferedReader(fileReader);  
        List<String> lines = new ArrayList<String>();  
        String line = null;  

        while ((line = bufferedReader.readLine()) != null) {  
            lines.add(line);  
        }  

        bufferedReader.close();  

        return lines.toArray(new String[lines.size()]);  
    }

public class Hotel_array {

      if (Menu.equalsIgnoreCase("S")) {
                save(hotel); 
            }
            if (Menu.equalsIgnoreCase("L")) {
                load(hotel); 
            }
        }
    }


    private static void save(String hotel[]) {
        try {
            PrintWriter pr = new PrintWriter("data.txt");
            for (int i = 1; i < 11; i++) {
                pr.println(hotel[i]);
            }
            pr.close();
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("No such file exists.");
        }
    }

    public static void load(String[] args) {
        FileLoad rf = new FileLoad();
        String file = "data.txt";
        try {
            String[] hotel = rf.readLines(file);
            for (String line : hotel) {
                System.out.println(line); // IT PRINTS FILE NOT LOADS TO ARRAY
            }
        } catch (IOException e) { 
            System.out.println("Unable to create " + file + ": " + e.getMessage());
        }
    }

}
tomaszsvd
  • 148
  • 2
  • 4
  • 15
  • 1
    What is the problem? – Diego Martinoia Feb 08 '16 at 15:46
  • right, i have a problem with Loading back the Saved data.txt file in to a existing hotel[] – tomaszsvd Feb 08 '16 at 15:55
  • 4
    first, don't reply as a comment: edit the question with the new information. second: what is the problem? Do you get exceptions? You don't know how to deserialize the hotel objects? try being as specific as possible. You are currently "saving" to file by using the toString method of the Hotel class (that's what println will call), so you should also post that method and/or an example of the saved file content so that we can see how to parse it. – Diego Martinoia Feb 08 '16 at 16:07
  • You do know arrays are zero-indexed, right? All the for-loops I see go from x=1..11, what about `hotel[0]`? – OneCricketeer Feb 08 '16 at 16:58
  • I'd recommend using Scanner for this. Just use `nextLine()` of Scanner class for each element of the array. `String names[] = new String[10]; for(int i = 0; i < names.length; i++) names[i] = scanner.nextLine();` Scanner seems alot easier for this situation. I may be wrong, but I'm just pointing it out. – Ashwin Gupta Feb 08 '16 at 17:31

2 Answers2

1

You could change your FileLoad class and add another method to write the array to the file, just to keep all the file IO in one class.

public class FileLoad {

    public static String[] readHotelArray(String filename) throws IOException {
        BufferedReader bufferedReader = new BufferedReader(new FileReader(filename));
        List<String> lines = new ArrayList<String>();
        String line = null;

        while ((line = bufferedReader.readLine()) != null) {
            lines.add(line);
        }

        bufferedReader.close();

        return lines.toArray(new String[lines.size()]);
    }

    public static void writeHotelArray(String filename, String[] hotel) throws IOException {
        BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(filename, false));
        //Write each string from the array to the file as a new line
        for (String s : hotel)
            bufferedWriter.write(s + "\n");
        bufferedWriter.flush();
        bufferedWriter.close();
    }
}

Note: Both methods are static so you don't have to instantiate a new object since there will always be only one method call on that object

Now you have to change the way you save and load the array in your Hotel_array class. You could use something like this:

//...
private static void save(String[] hotel) {
    try {
        FileLoad.writeHotelArray("data.txt", hotel);
    } catch (Exception e) {
        e.printStackTrace();
        System.out.println("No such file exists.");
    }
}

public static String[] load() {
    String file = "data.txt";
    String[] hotelArray = null;
    try {
        hotelArray = FileLoad.readHotelArray(file);
    } catch (IOException e) {
        System.out.println("Unable to create " + file + ": " + e.getMessage());
    }
    return hotelArray;
}
//...

and since parameters in java are always pass-by-value (more about that here) you need to return the String array in your load() method. And therefore you also have to change a tiny bit of code in the main method.
From:

//...
if (Menu.equalsIgnoreCase("L")) {
    load(hotel); 
}
//...

To:

//...
if (Menu.equalsIgnoreCase("L")) {
    hotel = load();
}
//...

Hope that helps a bit (:

Community
  • 1
  • 1
scsere
  • 621
  • 2
  • 15
  • 25
1

tomaszsvd, I will leave this here for your review... I thought it might help your Java learning curve. I encourage you to compare the load() method below with your original code. Also study the example output to see what is different.

fwiw, I like scsere's answer, it is a clean design. You should pursue that and mark it as the answer.


Let's focus on the code for Hotel_array.load( String[] args ).

Once Hotel_array.load() calls rf.readLines() you have 2 arrays in memory.

1st array:  Hotel_array's main()'s local variable "hotel".
2nd array:  load()'s local variable "hotel", which is a temporary variable.

Inside Hotel_array.load() remember that the args parameter ties back to main()'s "hotel" variable.

So load()'s local variable "hotel" has nothing to do with main()'s "hotel" variable.

Just to make this a little more clear I'm going to tweak your load() method:

Sample Output

$ javac *.java
$ cat data.txt 
alpha
beta
gamma
delta
$ java Hotel_array 
WELCOME TO THE HOTEL BOOKING 

Hotel Booking Options
A: To Add customer to a room
V: To View all rooms

E: To Display empty rooms
D: To Delete customer from a room
F: Find room from customer name

O: View rooms alphabetically by name
S: Save to file
L: Load from file
L
Loaded 4 lines from filedata.txt
args[1]=empty, will assign line=alpha
args[2]=empty, will assign line=beta
args[3]=empty, will assign line=gamma
args[4]=empty, will assign line=delta

Hotel Booking Options
A: To Add customer to a room
V: To View all rooms

E: To Display empty rooms
D: To Delete customer from a room
F: Find room from customer name

O: View rooms alphabetically by name
S: Save to file
L: Load from file
V
room 1 is occupied by alpha
room 2 is occupied by beta
room 3 is occupied by gamma
room 4 is occupied by delta
room 5 is empty
room 6 is empty
room 7 is empty
room 8 is empty
room 9 is empty
room 10 is empty

Hotel Booking Options
A: To Add customer to a room
V: To View all rooms

E: To Display empty rooms
D: To Delete customer from a room
F: Find room from customer name

O: View rooms alphabetically by name
S: Save to file
L: Load from file
^C$

Modified Hotel_array.load() method

public static void load(String[] args) {
    FileLoad rf = new FileLoad();
    String file = "data.txt";
    try {
        // ORIGINAL String[] hotel = rf.readLines(file);
        String[] tempHotelData = rf.readLines(file); // Note the different var name.
        System.out.println("Loaded "+tempHotelData.length+" lines from file"+file);
        int i = 1; // Following your convetion of staring from index #1.
        for (String line : tempHotelData ) {
            // ORIGINAL: System.out.println(line); // IT PRINTS FILE NOT LOADS TO ARRAY
            // NEW...
            // Let's print out what is oging on...
            // So let's assign "line" to the "args" array.
            // Remember that "args" ties back to main()'s "hotel" variable.
            System.out.println("args["+i+"]="+args[i]+", will assign line="+line);
            args[i] = line;
            i = i + 1;
        }
    } catch (IOException e) {
        // probably should say "Unable to LOAD" vs "Unable to CREATE"...
        System.out.println("Unable to create " + file + ": " + e.getMessage());
    }
}

Some additional things for you to think about...

1) Do you want to assign a line from a file if somebody is already in a room?
  (e.g. it isn't empty).

2) What happens if "data.txt" has more lines than you have rooms?
jgreve
  • 1,225
  • 12
  • 17
  • thank you for the help i can see what you mean, 1) Do you want to assign a line from a file if somebody is already in a room? (e.g. it isn't empty). This is still to be solved – tomaszsvd Feb 08 '16 at 23:08
  • @tomaszsvd, glad that was a bit helpful. You're at a fun point on the learning curve. Happy coding :-) (btw, I don't mean to break your load logic, nor push the requirements too far. If the purpose of loading & saving is only to duplicate room status at a point in time then looking for the 'next empty room' is over thinking it. If it is supposed to be an exact save/load you might want to add a warning if you get too few (or too many) lines from the data file). – jgreve Feb 09 '16 at 01:38