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?
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
I am new to java and have been trying to write how to search multidimensional arrays. My code works for elements found but when I enter an element that does not match, it does not printout anything. Please tell me what's wrong with my code.
import java.util.Scanner;
public class ArraySearch {
public static void main (String[] args){
Scanner input = new Scanner(System.in);
//lets create the array
int [] [] arrayOfInts = {{1, 2,3,4}, {5,6,7,8},{9,10,11,12}};
//create search variables
System.out.println("Enter the key number to search for in the array: ");
int key = input.nextInt();
boolean foundIt;
//perform search using a for loop
for (int i = 0; i <arrayOfInts.length; i++){
for (int j = 0; j <arrayOfInts[i].length; j++){
if (arrayOfInts[i][j] == key) {
foundIt = true;
if (foundIt) {
System.out.println("found " + key + " at row " +i+ " column " +j);
} else {
System.out.println(key + "is not in the array");
}
}
}
}
}
}
You should initialize your boolean to false, since local variables must be initialized before being used :
boolean foundIt = false;
Otherwise, if the key wasn't found, foundIt would be uninitialized when you access it in your if condition.
Not initializing foundIt should have given you a compliation error (The local variable foundIt may not have been initialized), but you have another error that hid this error. Your if statement that prints the output should be outside the for loops. Now it's inside the condition that finds a match, so it would only be evaluated if you found a match.
You can change your code to following. There are many issues in your code. You have to make correct order of {}, If you do so you needs to initialize foundIt
Scanner input = new Scanner(System.in);
//lets create the array
int[][] arrayOfInts = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}};
//create search variables
System.out.println("Enter the key number to search for in the array: ");
int key = input.nextInt();
boolean foundIt = false;
for (int i = 0; i < arrayOfInts.length; i++) {
for (int j = 0; j < arrayOfInts[i].length; j++) {
if (arrayOfInts[i][j] == key) {
System.out.println("found " + key + " at row " + i + " column " + j);
// if found it will change the foundIt to true
foundIt = true;
}
}
}
if (!foundIt) {
System.out.println(key + "is not in the array");
}
Your bracketing is wrong. The if - else statement
if (foundIt) {
System.out.println("found " + key + " at row " +i+ " column " +j);
} else
{System.out.println(key + "is not in the array");
}
Is inside the check of the for loop.
if (arrayOfInts[i][j] == key) {
You probably want to have it inside of the for loop to show the message for each match. But then you should just put a println message inside the if statement in the for loop
if (arrayOfInts[i][j] == key) {
System.out.println("found " + key + " at row " +i+ " column " +j);
And to print the other message when the key was never found, but this has to be done at the end. Make sure you initialize the boolean in the beginning!
boolean foundIt = false;
...
//at the end
if(!foundIt) {
System.out.println("found " + key + " at row " +i+ " column " +j);
}
// perform search using a for loop
for (int i = 0; i < arrayOfInts.length; i++) {
for (int j = 0; j < arrayOfInts[i].length; j++) {
if (arrayOfInts[i][j] == key) {
System.out.println("found " + key + " at row " + i + " column "
+ j);
return;
}
}
}
System.out.println(key + "is not in the array");
I just added a return on finding the desired element and cut/paste the else branch to the end of the loop.
Your System.out is only inside this if-block
if (arrayOfInts[i][j] == key)
so if you don't find something the is no printout
I would do it in this way:
...
for (int i = 0; i <arrayOfInts.length; i++){
for (int j = 0; j <arrayOfInts[i].length; j++){
if (arrayOfInts[i][j] == key) {
foundIt = true;
// Tell where you found it
System.out.println("found " + key + " at row " +i+ " column " +j);
}
}
}
// After all check whether you found something anytime
if(!foundIt){
System.out.println(key + "is not in the array");
}
...
It's because your print statements the if (foundIt) ... else block is within the if (arrayOfInts[i][j] == key) block. This means that if the int is not found, the code never enters that inner if check where you print.
You can move the "not found" to the end.
For example:
boolean foundIt = false;
// perform search using a for loop
for (int i = 0; i < arrayOfInts.length; i++)
{
for (int j = 0; j < arrayOfInts[i].length; j++)
{
if (arrayOfInts[i][j] == key)
{
foundIt = true;
System.out.println("found " + key + " at row " + i + " column " + j);
}
}
}
if (!foundIt)
{
System.out.println(key + "is not in the array");
}
Don't forget to initialize the foundIt to false first.
My Suggested Solution is :
bool foundit=false;
for (int i = 0; i <arrayOfInts.length; i++){
for (int j = 0; j <arrayOfInts[i].length; j++){
if (arrayOfInts[i][j] == key)
{
foundIt = true;
break;
System.out.println("found " + key + " at row " +i+ " column " +j);
}
}
}
if(!foundit)
{
system.out.println("Key not found in the array.")
}
This works:
import java.util.Scanner;
public class ArraySearch {
public static void main (String[] args){
Scanner input = new Scanner(System.in);
//lets create the array
int [] [] arrayOfInts = {{1, 2,3,4}, {5,6,7,8},{9,10,11,12}};
//create search variables
System.out.println("Enter the key number to search for in the array: ");
int key = input.nextInt();
//perform search using a for loop
for (int i = 0; i <arrayOfInts.length; i++){
for (int j = 0; j <arrayOfInts[i].length; j++){
if (arrayOfInts[i][j] == key) {
System.out.println("found " + key + " at row " +i+ " column " +j);
return;
}
}
}
System.out.println(key + " is not in the array");
}
}
Why:
commands in operatorif (arrayOfInts[i][j] == key) {} executing only if the element is found in array, so it is no need to use your boolean foundIt;. Use return to end executing the class, cos we have found what we wanted. The line System.out.println(key + " is not in the array"); should be after the two cycles so it will work only if we've checked each element of the two-dimensional array before.
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");
}
}
I have a code that will give me the coordinates of certain points in an array using user input. What code would I add to make the code output say that the address could not be found if the number in the array is not there? I'm pretty sure I need an else statement but I can't get it to work. Here is the code I have right now.
import java.util.Scanner;
public class LabActivityArray
{
public static void main (String[] args)
{
Scanner scanner = new Scanner (System.in);
int rows;
int columns;
int check1,check2;
System.out.println("Enter number of rows: ");
rows = scanner.nextInt();
System.out.println ("Now enter the number of columns: ");
columns = scanner.nextInt();
int[][] array = new int[rows][columns];
System.out.println("Enter the number to start the array: ");
int value = scanner.nextInt();
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < columns; j++)
{
array[i][j]=value++;
System.out.print(array[i][j] + " " );
}
System.out.println();
}
System.out.println("Please give one integer value to be checked in the array: ");
check1 = scanner.nextInt();
System.out.println ("Please give a second integer value to be checked in the array: ");
check2 = scanner.nextInt();
for ( int i = 0; i < rows; ++i )
{
for ( int j = 0; j < columns; ++j )
{
if ( array[i][j] == check1 )
{
System.out.print(array[i][j] + " is located at address array[" + i + "," + j + "]");
}
if ( array[i][j] == check2 )
{
System.out.print("\n" + array[i][j] + " is located at address array[" + i + "," + j + "]");
System.out.println();
}
}
}
}
}
step 1: make a flag say
boolean check1Found = false;
step 2: if you find the value, set the flag to true
if ( array[i][j] == check1 )
{
System.out.print(array[i][j] + " is located at address array[" + i + "," + j + "]");
check1Found = true;
}
step 3: after your loop is finished, print a message if that flag is still false
if(check1Found == false)
{
System.out.println("check 1 not found");
}
You could add two bool flag which are false at first but when the numbers youre searching are found, they are set to true.
bool foundFlag1 = false;
bool foundFlag2 = false;
Then
if ( array[i][j] == check2 ) {
foundFlag2 = true;
..
}
and do the same for check1.
If the flags are false, you know that you couldn't find those inputs!
You are almost right here. Here is the Pseudocode
Initialize Boolean Flag = false;
Search for number in array. if found set Flag = True.
After searching the number in array, check Flag.
If Flag = False, print "the address could not be found"
I would do this:
boolean check1Flag = false;
boolean check2Flag = false;
for ( int i = 0; i < rows; ++i )
{
for ( int j = 0; j < columns; ++j )
{
if ( array[i][j] == check1 )
{
System.out.println(array[i][j] + " is located at address array[" + i + "," + j + "]");
check1Flag = true;
}
if ( array[i][j] == check2 )
{
System.out.println(array[i][j] + " is located at address array[" + i + "," + j + "]");
check2Flag = true;
}
}
}
if(!check1Flag)
{
System.out.println("Can't find " + check1);
}
if(!check2Flag)
{
System.out.println("Can't find " + check2);
}
The flags are set to true when the array is found, so if either are false than that address could not be found.