Im creating a hotel reservation program. I need to store the array which have the details into a txt file and load it afterwards when running the program again..
my data is not storing into the hotel array
public static void Write(String[] hotel){
//storing information of the array into a text file
Scanner sc=new Scanner(System.in);
System.out.println("");
System.out.print("Do you want to write the data to a file(y/n) - ");
String SaveTheFile=sc.nextLine();
if(SaveTheFile.equalsIgnoreCase("y")){
try{
FileWriter file = new FileWriter("Hotel.txt");
PrintWriter pr = new PrintWriter(file);
for(int x =1;x<=10;x++){
pr.println(+x+":"+hotel[x]+":");
}
pr.close();
System.out.println("Write Successful");
System.out.println("");
Menu(hotel);
} catch (IOException e) {
System.err.println("Error!!!");
}
}else if(SaveTheFile.equalsIgnoreCase("n")){
//if the user entered 'n' going back to menu
Menu(hotel);
}else{
//if the user entered any other, displaying an error message
System.err.println("Please Enter 'y' or 'n' !!!");
Write(hotel);
}
}
public static String[] Load(String[] hotel){
String line = null;
String numSt,name;
int num;
System.out.println("");
Scanner sc = new Scanner(System.in);
try {
FileReader fr = new FileReader("Hotel.txt");
BufferedReader br = new BufferedReader(fr);
String str;
while ((str = br.readLine()) != null) {
String[] token = line.split(":");
numSt = token[0];
name = token[1];
num = Integer.parseInt(numSt);
hotel[num]=name;
}
br.close();
} catch (IOException e) {
System.out.println("file not found");
}
catch (NullPointerException f) {
System.out.println("Null pointer here...");
}
return hotel;
}
I found out the answer......
String line = "";
int counter = 0;
while ((line = br.readLine()) != null) {
numSt = line.split(":")[0];
name = line.split(":")[1];
counter = Integer.parseInt(numSt);
hotel[counter]=name;
counter++;
Thank u for spending your valuable time for helping me to sort this out :)