Array values being set for everything (Java) - java

In my code below, I am having an issue where I add the customer name to one room, but instead it adds the customer to every room. I can't figure out what in my code the issue is. I have tried removing the procedure but that still produced the same problem.
package test;
import java.util.*;
public class test {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String choice, custName = "";
int roomNum = 1;
String[] hotel = new String[12];
String[] customer = new String[12];
hotelInitialise(hotel);
custInitialise(customer);
while ( roomNum < hotel.length-1 ) {
for (int i = 0; i < hotel.length-1; i++) {
System.out.println("This is the Hotel Menu. Please choose from the following options:\n");
System.out.println("A: " + "This will add a new entry\n");
System.out.println("V: " + "View all rooms\n");
choice = input.next().toUpperCase();
if (choice.equals("A")) {
System.out.println("Enter room number(1-10)");
roomNum =input.nextInt();
System.out.println("Enter name for room " + roomNum + " : " ) ;
custName = input.next();
addNewBooking(hotel, custName);
System.out.println(" ");
}
if (choice.equals("V")) {
seeAllRooms(hotel, custName);
}
}
}
}
// When the program loads it will assign all the values of the array as being empty
private static void hotelInitialise( String hotelRef[] ) {
for (int x = 0; x < 11; x++){
hotelRef[x] = "Room " + x + " is empty.";
}
System.out.println( "Welcome to the Summer Tropic Hotel.\n");
}
private static void custInitialise (String custRef[]) {
for (int i = 0; i < 11; i++) {
custRef[i] = ", no customer has occupied this room";
}
}
private static void addNewBooking(String hotel[], String customer) {
for (int x =1; x <11; x++) {
if (hotel[x].equals("Room " + hotel[x] + " is empty."))
System.out.println("Room " + x + " is empty.");
else {
System.out.println("Room " + x + " is occupied by "+ customer);
}
}
}
private static void seeAllRooms(String hotel[], String customer) {
for (int i = 0; i < hotel.length-1; i++) {
int j=0;
String custName = customer;
hotel[j]= custName;
if (hotel[i].equals("Room " + i + " is empty."))
System.out.println("Room " + i + " is empty.");
else {
System.out.println("Room " + i + " is occupied by "+ hotel[j] + ".");
}
}
}
}

In addNewBooking method you have this line:
if (hotel[x].equals("Room " + hotel[x] + " is empty."))
However hotel[x] has a value of "Room x is empty" e.g. hotel[1] is "Room 1 is empty" So the final check is becoming "hotel[x].equals(Room Room x is empty is empty.)" which is never equals to your hotel[x]
You have to change your code to
if (hotel[x].equals("Room " + x + " is empty."))
//do something there like add the booking

Related

Find all matching elements in Array - Java

At the moment my code is only giving me the first matching result. The user inputs their desired room price and at the moment it will only display the first match. In the case the user inputs '60' to the console it should display 3 results. I imagine i'll need another forloop and if statement after it prints to the console but not sure how to execute
public static void secondMain() {
BufferedReader reader;
var lines = new ArrayList<String>();
var rooms = new ArrayList<Room>();
Room selectedRoom = null;
try {
reader = new BufferedReader(new FileReader("rooms.txt"));
String line = reader.readLine();
lines.add(line);
while (line != null) {
line = reader.readLine();
lines.add(line);
}
reader.close();
for (int i = 0; i < lines.size() - 1; i++) {
String[] words = lines.get(i).split(" ");
var room = new Room();
room.roomNum = Integer.parseInt(words[0]);
room.roomType = (words[1]);
room.roomPrice = Double.parseDouble(words[2]);
room.hasBalcony = Boolean.parseBoolean(words[3]);
room.hasLounge = Boolean.parseBoolean(words[4]);
room.eMail = (words[5]);
rooms.add(room);
}
var searchRoomPrice = input.nextDouble();
for (int i = 0; i < rooms.size(); i++) {
if (rooms.get(i).roomPrice == searchRoomPrice) {
selectedRoom = rooms.get(i);
break;
}
}
System.out.println("Room Number: " + selectedRoom.roomNum);
System.out.println("Room Type: " + selectedRoom.roomType);
System.out.println("Room Price: " + selectedRoom.roomPrice);
System.out.println("Balcony: " + selectedRoom.hasBalcony);
System.out.println("Lounge: " + selectedRoom.hasLounge);
System.out.println("Email: " + selectedRoom.eMail);
System.out.println("-------------------");
} catch (Exception e) {
e.printStackTrace();
}
}
Any other information needed feel free to ask
If you only want to print the information move the print commands inside the loop and remove the break i.e.
for(int i = 0; i < rooms.size(); i++){
if(rooms.get(i).roomPrice == searchRoomPrice){
selectedRoom = rooms.get(i);
System.out.println("Room Number: " + selectedRoom.roomNum);
System.out.println("Room Type: " + selectedRoom.roomType);
System.out.println("Room Price: " + selectedRoom.roomPrice);
System.out.println("Balcony: " + selectedRoom.hasBalcony);
System.out.println("Lounge: " + selectedRoom.hasLounge);
System.out.println("Email: " + selectedRoom.eMail);
System.out.println("-------------------");
}
}
You could also save all the objects in a list with the first loop and then in a second loop iterate over the list and print the information i.e.
List<Room> roomList = new ArrayList<Room>();
for(int i = 0; i < rooms.size(); i++){
if(rooms.get(i).roomPrice == searchRoomPrice){
roomList.add(rooms.get(i));
}
}
for(Room room : roomList){
System.out.println("Room Number: " + room.roomNum);
System.out.println("Room Type: " + room.roomType);
System.out.println("Room Price: " + room.roomPrice);
System.out.println("Balcony: " + room.hasBalcony);
System.out.println("Lounge: " + room.hasLounge);
System.out.println("Email: " + room.eMail);
System.out.println("-------------------");
}
I notice 2 things:
You are using a break; here:
if(rooms.get(i).roomPrice == searchRoomPrice){
selectedRoom = rooms.get(i);
break;
}
So you are stopping the loop after the first match.
Here:
for (int i = 0; i < lines.size() - 1; i++)
Is there a reason to use that minus 1?

Getters are not visible in other classes

I'm learning Java for a week, and now i have a problem, because i want to print all Arraylist in method printArray, but the method don't see getName() and other methods and I don't know how to solve my problem. Thanks a lot for your help.
If you can, please show my what I;m doing wrong.
Class Positions:
public class Positions {
List<Positions> list = new ArrayList<>(15);
int ageAdd;
int IDAdd;
String nameAdd;
int counter;
String name;
int age;
int ID;
public Positions(String name, int age, int ID) {
this.name = name;
this.age = age;
this.ID = ID;
}
public Positions() {
this("", 0, 0);
}
//there are methods:
//adding element
//removing element
//changing values
//etc
public String getName() {
return name;
}
public int getAge() {
return age;
}
public int getID() {
return ID;
}
public void printArray() {
for (int i = 0; i < list.size(); i++) {
System.out.println(i + " : " + " NAME: " + list.getName(i) + " AGE: " + list.getAge(i) + " ID: " list.getID(i));
}
}
Class main:
public class ArrayList2
{
public static void main (String[] args)
{
Positions p = new Positions();
System.out.println("----LISTA TABLICOWA-----");
System.out.println("Co chcesz wykonać? ");
System.out.println("1. Dodac element do listy. ");
System.out.println("2. Usunac elemnt z listy.");
System.out.println("3. Wstawić na dowolna pozycje.");
System.out.println("4. Rozmiar listy.");
System.out.println("5. Zmienic wartosc na podanym indeksie.");
System.out.println("6. Wyświetlić listę. ");
while(true) {
System.out.println("podaj pozycję: ");
Scanner ch = new Scanner(System.in);
int choice= ch.nextInt();
switch (choice)
{
case 1:
{
p.addPosition(); //?
break;
}
case 2:
{
p.removePosition();
break;
}
case 3:
{
p.setOnAnyPosition();
break;
}
case 4:
{
p.ArraySizeShow();
break;
}
case 5:
{
p.changePosition();
break;
}
case 6:
{
p.printArray();
break;
}
}
}
}
}
You simply have a problem with the array access:
Instead of using:
public void printArray() {
for (int i = 0; i < list.size(); i++) {
System.out.println(i + " : " + " NAME: " + list.getName(i) ...);
}
}
You should use:
public void printArray() {
for (int i = 0; i < list.size(); i++) {
System.out.println(i + " : " + " NAME: " + list.get(i).getName() ...);
}
}
because you want to get the name of a specific element, and in OO languages, that usually means calling the method on the object itself.
Ijn your example, you have a list that contains objects that contains a name. So if you want to access the name from the list, you need to first get an element then get his name.
HTH.
Try to change method with below code. Hope it would help.
public void printArray() {
for (int i = 0; i < list.size(); i++) {
System.out.println(i + " : " + " NAME: " + list.get(i).getName() + " AGE: " + list.get(i).getAge() + " ID: " list.get(i).getID());
}
}
To loop over your list either use
for (int i = 0; i < list.size(); i++) {
Positions p = list.get(i);
System.out.println(i + " : " + " NAME: " + p.getName() + " AGE: " + p.getAge() + " ID: " + p.getID());
}
or
int index =0;
for (Positions p : list) {
System.out.println(index++ + " : " + " NAME: " + p.getName() + " AGE: " + p.getAge() + " ID: " + p.getID());
}

Using JOptionPane to print reports

Okay so now I got my code to compile and run, but the output is incorrect now. I need to be able to select an option and then for 2, and 3 have 3 additional options after selecting that option. How should I adapt my coding to do this?
Task:
List of all information
List of all surgeries for a specific doctor (prompt for the doctor)
List of all surgeries of a specific type (prompt for the surgery type)
Total amount of surgery fees paid to each Doctor
Average Fees
Data File (patient.txt):
11111,Smith,Norris,Thyroid,1000.00
11112,Obama,Norris,Lasek,500.00
11113,Hoover,Norris,Dental,100.00
11114,Cena,Norris,Lasek,500.00
11115,Leto,Norris,Thyroid,1000.00
22221,Clark,Bond,Thyroid,1000.00
22222,Chang,Bond,Lasek,500.00
22223,Dent,Bond,Dental,100.00
22224,Nixon,Bond,Lasek,500.00
22225,Washington,Bond,Dental,100.00
33331,Jones,Lee,Dental,100.00
33332,Ross,Lee,Lasek,500.00
33333,Gates,Lee,Thyroid,1000.00
33334,Johnson,Lee,Thyroid,1000.00
33335,Carter,Lee,Dental,100.00
Code so far for reference:
package Patient_Reports_Package;
/**
* Created by bzink on 8/28/2015.
*/
import javax.swing.*;
import java.io.*;
import java.util.StringTokenizer;
/**
* The Patient_Reports_File class reads the data file into an array, and then has a menu for 5 reports.
*/
class Patient_Reports {
private final int[] id = new int[100];
private final String[] patient = new String[100];
private final String[] doctor = new String[100];
private final String[] surgery = new String[100];
private final double[] cost = new double[100];
private int count = -1;
private int i;
public static void main (String[] args) {
int selection;
String report_number;
Patient_Reports patient = new Patient_Reports();
patient.start_system();
report_number = patient.menu();
selection = Integer.parseInt(report_number);
while (selection !=6) {
if (selection == 1) {
patient.allInformationReport();
} else if (selection == 2) {
patient.surgeryDoctorReport();
} else if (selection == 3) {
patient.surgeryTypeReport();
} else if (selection == 4) {
patient.doctorFeesReport();
} else if (selection == 5) {
patient.averageFeesReport();
}
report_number = patient.menu();
selection = Integer.parseInt(report_number);
}//while loop
patient.writeReports();
System.exit(0);
}//main
//Read Data File into Array
private void start_system() {
String newLine;
try {
//define a file variable for Buffered read
BufferedReader Patient_Reports = new BufferedReader(new java.io.FileReader("C:\\Users\\Brandon\\" +
"Downloads\\Patient_Reports_File\\patient.txt"));
//read lines in file until there are no more lines in the file to read
while ((newLine = Patient_Reports.readLine()) != null) {
//there is a "," between each data item in each line
StringTokenizer delimiter = new StringTokenizer(newLine, ",");
count = count + 1;
id[count] = Integer.parseInt(delimiter.nextToken());
patient[count] = delimiter.nextToken();
doctor[count] = delimiter.nextToken();
surgery[count] = delimiter.nextToken();
cost[count] = Double.parseDouble(delimiter.nextToken());
}//while loop
Patient_Reports.close();
}//end try
catch (IOException error) {
//there was an error on the file writing
System.out.println("Error on file read " + error);
}//end catch
}//end start_system
//Report Menu
private String menu () {
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("Id ").append(" \n");
stringBuilder.append("Patient ").append(" \n");
stringBuilder.append("Doctor ").append(" \n");
stringBuilder.append("Surgery ").append(" \n");
stringBuilder.append("Cost ").append(" \n");
for (int i = 0; i < 6; i++) {
stringBuilder.append(i).append(" Name"+i).append('\n');
}
String startTag ="<font size='2' color='red'>";
String endTag = "</font>";
stringBuilder.append(startTag).append("Some content").append(endTag);
JOptionPane.showMessageDialog(null, stringBuilder.toString());
return stringBuilder.toString();
}//end menu\
/*
//Report Menu
private String menu() {
String report;
String Output = "Reports" + "\n" + "1. All_Information_Report" + "\n" +
"2. Surgeries_Doctor_Report" + "\n" +
"3. Surgeries_Type_Report" + "\n" +
"4. Doctor_Fees_Report" + "\n" +
"5. Average_Fees_Report" + "\n" +
"6. Exit" + "\n" +
" " + "\n" +
"Select a Report >";
report = JOptionPane.showInputDialog(null,
Output, "", JOptionPane.QUESTION_MESSAGE);
return report;
}//end menu\
*/
//Report containing all of the information
private void allInformationReport() {
System.out.println("All Information Report");
for (i = 0; i <= count; ++i) {
System.out.println(id[i] + " " + patient[i] + " " + doctor[i] + " " + surgery[i] + " " + cost[i] + " ");
}//for loop
}//end report
/* void selectDoctor()
{
//select doctor
String doctorOutput;
//int intNum=0,intNum1=0,i,x=-1;
count=count+1;
doctorOutput = "Enter the Doctor's Name";
doctor[count] =JOptionPane.showInputDialog(null,doctorOutput,
"",JOptionPane.QUESTION_MESSAGE);
}//end select doctor
//Start Doctor Menu
public static void doctorMenu (String[] args) {
int selection;
String doctorName;
Patient_Reports doctor = new Patient_Reports();
doctor.start_system();
doctorName = doctorMenu();
selection = Integer.parseInt(doctorName);
while (selection !=4) {
if (selection == 1) {
doctor.norrisSurgeries();
} else if (selection == 2) {
doctor.bondSurgeries();
} else if (selection == 3) {
doctor.leeSurgeries();
}
doctorName = doctorMenu();
selection = Integer.parseInt(doctorName);
}//while loop
doctor.writeReports();
System.exit(0);
}//End Doctor Menu
//Report on all surgeries by Dr. Norris
private void norrisSurgeries() {
System.out.println("Norris Surgeries Report");
for (i = 0; i <= count; ++i) {
System.out.println(doctor[i] + " " + surgery[i] + " ");
}//for loop
}//end report
//Report on all surgeries by Dr. Bond
private void bondSurgeries() {
System.out.println("Bond Surgeries Report");
for (i = 0; i <= count; ++i) {
System.out.println(doctor[i] + " " + surgery[i] + " ");
}//for loop
}//end report
//Report on all surgeries by Dr. Lee
private void leeSurgeries() {
System.out.println("Lee Surgeries Report");
for (i = 0; i <= count; ++i) {
System.out.println(doctor[i] + " " + surgery[i] + " ");
}//for loop
}//end report
*/
//Report on all surgeries of a specific doctor (prompt for the doctor)
private void surgeryDoctorReport() {
System.out.println("Surgeries Doctor Report");
for (i = 0; i <= count; ++i) {
System.out.println(id[i] + " " + patient[i] + " " + doctor[i] + " " + surgery[i] + " " + cost[i] + " ");
}//for loop
}//end report
/*
void selectSurgery()
{
//select surgery
String surgeryOutput;
//int intNum=0,intNum1=0,i,x=-1;
count=count+1;
surgeryOutput = "Enter the Surgery Type";
doctor[count] =JOptionPane.showInputDialog(null,surgeryOutput,
"",JOptionPane.QUESTION_MESSAGE);
}//end select surgery
*/
//Report on all surgeries of a specific type(Prompt for the surgery type)
private void surgeryTypeReport() {
System.out.println("Surgeries Type Report");
for (i = 0; i <= count; ++i) {
System.out.println(id[i] + " " + patient[i] + " " + doctor[i] + " " + surgery[i] + " " + cost[i] + " ");
}//for loop
}//end report
//Report on the total amount of fees paid to each doctor
private void doctorFeesReport() {
System.out.println("Doctor Fees Report");
for (i = 0; i <= count; ++i) {
System.out.println(id[i] + " " + patient[i] + " " + doctor[i] + " " + surgery[i] + " " + cost[i] + " ");
}//for loop
}//end report
//Report on the Average Fee
private void averageFeesReport() {
System.out.println("Average Fees Report");
for (i = 0; i <= count; ++i) {
System.out.println(id[i] + " " + patient[i] + " " + doctor[i] + " " + surgery[i] + " " + cost[i] + " ");
}//for loop
}//end report
//Store Data File in Array
private void writeReports()
{
try {
BufferedWriter Patient_Reports = new BufferedWriter(new java.io.FileWriter("patient_out.txt"));
for (i = 0; i <= count; ++i) {
//put "," between each data item in the file
Patient_Reports.write(id[i] + "," + patient[i] + "," + doctor[i] + "," +
surgery[i] + "," + cost[i] + ",");
//write a new line in the file
Patient_Reports.newLine();
}//for loop
Patient_Reports.close();
}//end try
catch (IOException error) {
//there was an error on the write to file
System.out.println("Error on file write " + error);
}//end error
}//end write_reports
}
'
Use String or StringBuilder or StringBuffer to do this. But instead of String use either StringBuilder or StringBuffer. Since for String, you need some extra objects for String manipulation.
Ex:
StringBuilder sb = new StringBuilder();
sb.append("Id ").append(" Name\n");
for (int i = 0; i < 10; i++) {
sb.append(i).append(" Name"+i).append('\n');
}
JOptionPane.showMessageDialog(null, sb.toString());
Use HTML tags to produce better formatted results like <font>, <table>, etc.
Ex:
String startTag ="<font size='2' color='red'>";
String endTag = "</font>";
sb.append(startTag+"Some content"+endTag);

Struggling with my procedure in Java

I'm currently struggling to make my procedures to work. I'm having to do this all as objects This is what I have in my main file currently:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
Room[] myHotel = new Room[6];
//myHotel[x] = new Room();
myHotel[0] = new Room();
myHotel[1] = new Room();
myHotel[2] = new Room();
myHotel[3] = new Room();
myHotel[4] = new Room();
String roomName = null;
String choice;
int roomNum = 0;
initialise(myHotel);
while ( roomNum < 5 )
{
System.out.println("Hotel Booking Options");
System.out.println("V: To View all rooms");
System.out.println("A: To Add a customer to a room");
choice = input.next();
if (choice.equals("V")) //views all the rooms
{
view(myHotel, roomName);
}
if (choice.equals("A")) //To add a customer to a room
{
System.out.println("Enter room number (0-5) or 6 to stop:" );
roomNum = input.nextInt();
System.out.println("Enter name for room " + roomNum + " : " ) ;
roomName = input.next();
myHotel[roomNum].mainName = roomName ;
//myHotel[roomNum].setName(roomName);
add(myHotel, roomName);
System.out.println(" ");
}
}
}
private static void initialise( Room hotelRef[] ) {
for (int x = 0; x < 5; x++ ) hotelRef[x].mainName = "empty";
System.out.println( "initilise ");
}
public static void view(Room myHotel[], Room roomName){
for (int x = 0; x <5; x++)
{
int z = 0;
Room Roomname = roomName;
myHotel[z]= Roomname;
if (myHotel[x].mainName.equals("empty"))
System.out.println("room " + x + " is empty");
else {
System.out.println("room " + x + " occupied by " + myHotel[x].mainName);
//System.out.println("room " + x + " is occupied by "+ myHotel[x]);
}
}
}
private static void add(Room myHotel[], String roomName){
for (int x = 0; x <5; x++)
{
int z = 0;
String Roomname = roomName;
myHotel[z]= Roomname;
if (myHotel[x].mainName.equals("empty"))
{
System.out.println("room " + x + " is empty");
}
else {
System.out.println("room " + x + " is occupied by "+ myHotel[x]);
}
}
}
}
In my other .java file with the object variables:
public class Room {
String mainName;
//private String mainName;
int guestsInRoom;
public Room() {
mainName = "k";
System.out.println("made a room ");
}
public void setName(String aName) {
System.out.println("add name class method ");
mainName = aName;
}
public String getName() {
return mainName;
}
}
I'm not sure how to fix line 54 - view(myHotel, roomName); Sorry if my variable names are confusing and misleading...

For loop populates whole instead of one instance

I'm creating a booking system in Java to prevent double bookings i have created a for loop that should change a Boolean to booked once the booking is made however it is changing all the bookings to booked when i only want one instance of booking so no one else can make a booking.
public static boolean booked;
private void FSubmitActionPerformed(java.awt.event.ActionEvent evt) {
for ( int i = 0; i < Airplane.Fseat.length; i++)
{
String seat = FCol.getSelectedItem().toString() + FRow.getSelectedItem().toString();
String items = Snack.getSelectedItem().toString() + " " + Drink.getSelectedItem().toString();
Airplane.Fseat[i] = seat;
Airplane.item[i] = items;
if (Airplane.Fseat[i] != null)
{
System.out.println("Seat number is First class " + Airplane.Fseat[i].toString() + "\n" +"Food and drink " + " " + Airplane.item[i].toString());
i++;
}
else
{
System.out.println("Cannot book already taken");
}
}
You have not put any condition to check, how a particular seat will be set selected.
So you will need to modify your code as:
for ( int i = 0; i < Airplane.Fseat.length; i++)
{
String seat = FCol.getSelectedItem().toString() + FRow.getSelectedItem().toString();
String items = Snack.getSelectedItem().toString() + " " + Drink.getSelectedItem().toString();
if(your_condition_to_check_if_this_seat_is_selcted ){
Airplane.Fseat[i] = seat;
Airplane.item[i] = items;
}
if (Airplane.Fseat[i] != null)
{
System.out.println("Seat number is First class " + Airplane.Fseat[i].toString() + "\n" +"Food and drink " + " " + Airplane.item[i].toString());
i++;
}
else
{
System.out.println("Cannot book already taken");
}
}

Categories