Removing object from array and replacing it with object from another array - java

The problem I have encountered is as follows: I have created two array representing docking spaces for ships. The first array ship object be saved in the array and if there is no space then it will be added to a waiting list array. But when I remove an object from the first array the object from the waiting list array is not removed and added.
The dock can accommodate three sizes of ship; cargo, container and super-container. The rows are made up of 5 small and 3 medium and 2 large. A cargo ship (small) can berth in any available space. A container ship (medium) can berth in the medium space and large, but not in small spaces. A super-container can only fit in large space.
So if I enter shipName3 and Super-Container for example and there is already two Super-Container's it adds to the waiting list but when I remove a Super-Container from the dock it does not remove a ship from the waiting list and add it to the dock Can you help? Here's my dock method:
import java.util.*;
public class Main {
static Scanner scan = new Scanner(System.in);
private static Ship[] dock1 = new Ship[10];
private static Ship[] waitingList = new Ship[10];
public static void main(String[] args) {
menu();
}
public static void menu() {
Scanner scan = new Scanner(System.in);
while (true) {
System.out.println("Choose an option: 1-3");
System.out.println("1. Dock");
System.out.println("2. Undock");
System.out.println("3. Status");
int menu = scan.nextInt();
switch (menu) {
case 1:
System.out.println("1. Dock");
dock();
break;
case 2:
System.out.println("2. Undock");
undock();
break;
case 3:
System.out.println("3. Status");
printDock();
printWaitingList();
break;
case 4:
System.out.println("4. Exit");
System.exit(0);
default:
System.out.println("No such option");
break;
}
}
}
public static void dock() {
System.out.println("Enter ship's name: ");
String name = scan.nextLine();
System.out.println("Enter ship's size: ");
String size = scan.nextLine();
System.out.println("Enter the ships dock:");
//Check if the dock number is valid
int i = Integer.valueOf(scan.nextLine());
if (i >= 0 && i < 10 && dock1[i] == null) {
int c = 0;
int co = 0;
int sco = 0;
for (int j = 0; j < dock1.length; j++) {
if (dock1[j] != null && dock1[j].getShipSize().equals("Cargo")) {
c++;
}
if (dock1[j] != null && dock1[j].getShipSize().equals("Container")) {
co++;
}
if (dock1[j] != null && dock1[j].getShipSize().equals("Super-Container")) {
sco++;
}
}
if (c < 10 && co < 5 && sco < 2) {
//Add ship to the dock
dock1[i] = new Ship(name, size);
System.out.println("Enough space you can dock");
System.out.println("Ship has been docked");
} else {
System.out.println("You cannot dock");
waitingList(name,size);
}
} else {
System.out.println("Couldn't dock");
waitingList(name, size);
}
}
public static void undock() {
System.out.println("Status of ships: ");
printDock();
System.out.println("Enter ship's name to undock: ");
String name = scan.nextLine();
System.out.println("Enter ship's size to undock: ");
String size = scan.nextLine();
for (int i = 0; i < dock1.length; i++) {
if (dock1[i] != null && dock1[i].getShipName().equals(name)) {
dock1[i] = null;
System.out.println("Ship removed");
//break;
///HERE CHECK IF SHIP IN DOCK
for (int j = 0; j < dock1.length; j++) {
if (dock1[j] == null) {
//Add ship to the dock
dock1[j] = new Ship(name, size);
System.out.println("Move ship from waiting list to dock 1");
break;
} else {
System.out.println("No space in dock1");
return;
}
}
} else {
System.out.println("Ship not docked here");
break;
}
}
}
public static void waitingList(String name, String size){
System.out.println("Dock 1 is full, ship will try to be added to Waiting List");
for (int i = 0; i < dock1.length; i++) { //waitingList?
if (waitingList[i] == null) {
//Add ship to the dock
waitingList[i] = new Ship(name, size);
System.out.println("Enough space added to waiting list");
break;
} else {
System.out.println("No space on waiting list, ship turned away");
return;
}
}
}
public static void printDock() {
System.out.println("Docks:");
for (int i = 0; i < dock1.length; i++) {
if (dock1[i] == null) {
System.out.println("Dock " + i + " is empty");
} else {
System.out.println("Dock " + i + ": " + dock1[i].getShipName() + " " + dock1[i].getShipSize());
}
}
}
private static void printWaitingList() {
System.out.println("Waiting List:");
for (int i = 0; i < waitingList.length; i++) {
if (waitingList[i] == null) {
System.out.println("Dock " + i + " is empty");
} else {
System.out.println("Dock " + i + ": " + waitingList[i].getShipName() + " " + waitingList[i].getShipSize());
}
}
}
}
Ship class
public class Ship {
private String shipName;
private String shipSize;
public String getShipName() {
return shipName;
}
public void setShipName(String shipName) {
this.shipName = shipName;
}
public String getShipSize() {
return shipSize;
}
public void setShipSize(String shipSize) {
this.shipSize = shipSize;
}
public Ship(String shipName, String shipSize) {
this.shipName = shipName;
this.shipSize = shipSize;
}
}
I put my attempt in the undock method.

Please check your undock method in that you are removing from dock1 array and again you are adding to same object to dock1 array but there is no code to remove object from waitingList array simply update your loop in undock method as mentioned below
for (int i = 0; i < dock1.length; i++) {
if (dock1[i] != null && dock1[i].getShipName().equals(name)) {
dock1[i] = null;
System.out.println("Ship removed");
// break;
/// HERE CHECK IF SHIP IN DOCK
for (int j = 0; j < waitingList.length; j++) {
if (dock1[i] == null) {
// Add ship to the dock
dock1[i] = new Ship(waitingList[j].getShipName(), waitingList[j].getShipSize());
System.out.println("Move ship from waiting list to dock 1");
waitingList[j]=null;
break;
} else {
System.out.println("No space in dock1");
return;
}
}
} else {
System.out.println("Ship not docked here");
break;
}
}
I have changed inner loop iteration so it will loop to the size of waitingList array because we need to remove object from waitingList aray and add to dock1 array.Also i am runtime getting the shipname and shipsize from waitingList array so that it will add object from waitingList to dock1 array. I have tested code to my machine working here hope it will help you.

In your undock method, you remove the ship at the i'th position in dock1 array by setting it to null. This is ok but then you have a for loop that runs through all of the ships in dock1 looking for one with a null valued one. You aready know the one you just removed is null because you just set it to that value. Then you set it equal to a new ship that has the exact name and size of the one you removed (essentially putting the ship back). Instead, you want the for loop to traverse your list of waiting ships to find one that matches the space of the ship you just removed.
Replace:
for (int j = 0; j < dock1.length; j++) {
if (dock1[j] == null) {
//Add ship to the dock
dock1[j] = new Ship(name, size);
System.out.println("Move ship from waiting list to dock 1");
break;
} else {
System.out.println("No space in dock1");
return;
}
}
with
for (int j = 0; j < waitingList.length; j++) {
if (waitingList[j].getShipSize() <= size) {
//Add ship to the dock
dock1[i] = waitingList[j];
System.out.println("Move ship from waiting list to dock 1");
return;
}
}
System.out.println("No space in dock1");
return;

Related

How can I update the data inside of an array to be false instead of true?

This program is to reserve time available from three different games. So far in the program, I had printed the two different menus on that shows the game and the other one shows the available time Slots. the Program is set to be an infinite loop so other users have the chance to pick a game and reserve time as well. This is where my problem comes, the second time the program runs it stills displays the time that was previously picked.
import java.util.Scanner;
public class GameReservationSystem {
public static Scanner input = new Scanner(System.in);
static String[] timeSlots = {"1-2pm", "2-3pm", "3-4pm", "4-5pm"};
static String[] Games = {"Backganmon", "Chess", "Dominoes"};
static boolean avaliableTime[][] = new boolean[Games.length][timeSlots.length];
static int userChoice;
public static void main(String[] args) {
for (int i = 0; i < Games.length; i++) {
for (int j = 0; j < timeSlots.length; j++) {
avaliableTime[i][j] = true;
}
}
mainMenu();
}
public static void mainMenu() {
while (true) {
characterPrint('-');
for (int i = 0; i < Games.length; i++) {
System.out.print(i + ". ");
System.out.println(Games[i]);
}
characterPrint('-');
System.out.println("input a number to choose your game!");
userChoice = input.nextInt();
reserveMenu(userChoice);
}
}
public static void reserveMenu(int userChoice) {
int reserveTime = 0;
if (userChoice >= 0 && userChoice < Games.length) {
characterPrint('-');
System.out.println("This are the avaliable times to play" + Games[userChoice]);
for (int i = 0; i < timeSlots.length; i++) {
System.out.print(i + ". ");
System.out.println(timeSlots[i]);
}
characterPrint('-');
System.out.println("Input a number to reserve a time: ");
reserveTime = input.nextInt();
}
if (reserveTime >= 0 && reserveTime < timeSlots.length) {
avaliableTime[userChoice][reserveTime] = false;
System.out.println("You have succesfully reserve a time to play " + Games[userChoice] + " at" + timeSlots[reserveTime]);
}
}
public static void characterPrint(char c) {
for (int i = 0; i < 30; i++) {
System.out.print(c);
}
System.out.println();
}
}
In fact, your problem isn't that you didn't change the boolean values in your table from true to false. Instead, your problem is that you didn't use information in the table before you make reservations. What you were doing is to always set that value to false and print "succesfully reserve", without checking whether that time has already been reserved by someone else.
Try the following code. I also add some codes to handle invalid input number.
By the way, "avaliableTime" looks like a typo, so I changed it to "availableTime".
import java.util.Scanner;
public class GameReservationSystem {
public static Scanner input = new Scanner(System.in);
static String[] timeSlots = {"1-2pm", "2-3pm", "3-4pm", "4-5pm"};
static String[] Games = {"Backganmon", "Chess", "Dominoes"};
static boolean availableTime[][] = new boolean[Games.length][timeSlots.length];
static int userChoice;
public static void main(String[] args) {
for (int i = 0; i < Games.length; i++) {
for (int j = 0; j < timeSlots.length; j++) {
availableTime[i][j] = true;
}
}
mainMenu();
}
public static void mainMenu() {
while (true) {
characterPrint('-');
for (int i = 0; i < Games.length; i++) {
System.out.print(i + ". ");
System.out.println(Games[i]);
}
characterPrint('-');
System.out.println("input a number to choose your game!");
userChoice = input.nextInt();
reserveMenu(userChoice);
}
}
public static void reserveMenu(int userChoice) {
int reserveTime = 0;
if (userChoice >= 0 && userChoice < Games.length) {
characterPrint('-');
System.out.println("This are the avaliable times to play" + Games[userChoice]);
for (int i = 0; i < timeSlots.length; i++) {
if (availableTime[userChoice][i]) {
//if false, this time is not available and should not be displayed.
System.out.print(i + ". ");
System.out.println(timeSlots[i]);
}
}
characterPrint('-');
System.out.println("Input a number to reserve a time: ");
reserveTime = input.nextInt();
}else {
//handle unexpected game number.
System.out.println("Invalid game number, please try again.");
}
if (reserveTime >= 0 && reserveTime < timeSlots.length) {
//what if someone typed 0 although 0 wasn't displayed? (0 wasn't displayed, for example, because it has been reserved by someone else.)
//So you should check whether it is available by the following line.
if (availableTime[userChoice][reserveTime]) {
//if true, this time hasn't been reserved, so it is a valid input.
availableTime[userChoice][reserveTime] = false;
System.out.println("You have succesfully reserve a time to play " + Games[userChoice] + " at" + timeSlots[reserveTime]);
}else {
//if already false, this time has already been reserved by someone else,
//thus it is an invalid input.
System.out.println("This time has already been reserved, please try again.");
}
}else {
System.out.println("Invalid time number, please try again.");
}
}
public static void characterPrint(char c) {
for (int i = 0; i < 30; i++) {
System.out.print(c);
}
System.out.println();
}
}

Can only remove object from index 0 in array

The problem I have encountered is as follows: I have created two arrays representing docking spaces for ships. The first array (dock1[]) the ship object (shipName and size - usually Super-Container) can be saved in the array. If I want to remove object from dock1[] I enter the shipName to remove it.
But I can only remove the ship object from the first space (index 0) in the array and not from any other space i.e. index 1,2,3.
Can you help? Here's my dock class, problem in undock() if statement:
import java.util.*;
public class Main {
static Scanner scan = new Scanner(System.in);
private static Ship[] dock1 = new Ship[10];
private static Ship[] waitingList = new Ship[10];
public static void main(String[] args) {
menu();
}
public static void menu() {
Scanner scan = new Scanner(System.in);
while (true) {
System.out.println("Choose an option: 1-3");
System.out.println("1. Dock");
System.out.println("2. Undock");
System.out.println("3. Status");
int menu = scan.nextInt();
switch (menu) {
case 1:
System.out.println("1. Dock");
dock();
break;
case 2:
System.out.println("2. Undock");
undock();
break;
case 3:
System.out.println("3. Status");
printDock();
printWaitingList();
break;
case 4:
System.out.println("4. Exit");
System.exit(0);
default:
System.out.println("No such option");
break;
}
}
}
public static void dock() {
System.out.println("Enter ship's name: ");
String name = scan.nextLine();
System.out.println("Enter ship's size: ");
String size = scan.nextLine();
System.out.println("Enter the ships dock:");
//Check if the dock number is valid
int i = Integer.valueOf(scan.nextLine());
if (i >= 0 && i < 10 && dock1[i] == null) {
int c = 0;
int co = 0;
int sco = 0;
for (int j = 0; j < dock1.length; j++) {
if (dock1[j] != null && dock1[j].getShipSize().equals("Cargo")) {
c++;
}
if (dock1[j] != null && dock1[j].getShipSize().equals("Container")) {
co++;
}
if (dock1[j] != null && dock1[j].getShipSize().equals("Super-Container")) {
sco++;
}
}
if (c < 10 && co < 5 && sco < 2) {
//Add ship to the dock
dock1[i] = new Ship(name, size);
System.out.println("Enough space you can dock");
System.out.println("Ship has been docked");
} else {
System.out.println("You cannot dock");
waitingList(name, size);
}
} else {
System.out.println("Couldn't dock");
waitingList(name, size);
}
}
public static void undock() {
System.out.println("Status of ships: ");
printDock();
System.out.println("Enter ship's name to undock: ");
String name = scan.nextLine();
for (int i = 0; i < dock1.length; i++) {
if (dock1[i] != null && dock1[i].getShipName().equals(name)) { //ONLY FINDING in ARRAY 0
dock1[i] = null;
System.out.println("Ship removed");
/// HERE CHECK IF SHIP IN DOCK
for (int j = 0; j < waitingList.length; j++) {
if (dock1[i] == null && waitingList[j] != null) {
// Add ship to the dock
dock1[i] = new Ship(waitingList[j].getShipName(), waitingList[j].getShipSize());
System.out.println("Move ship from waiting list to dock 1");
waitingList[j] = null;
return;
} else {
// System.out.println("No space in dock");
return;
}
}
} else {
System.out.println("Ship not docked here");
break;
}
}
}
public static void waitingList(String name, String size) {
System.out.println("Dock 1 is full, ship will try to be added to Waiting List");
for (int i = 0; i < waitingList.length; i++) {
if (waitingList[i] == null) {
//Add ship to the dock
waitingList[i] = new Ship(name, size);
System.out.println("Enough space added to waiting list");
return;
} else {
}
}
System.out.println("No space on waiting list, ship turned away.");
}
public static void printDock() {
System.out.println("Docks:");
for (int i = 0; i < dock1.length; i++) {
if (dock1[i] == null) {
System.out.println("Dock " + i + " is empty");
} else {
System.out.println("Dock " + i + ": " + dock1[i].getShipName() + " " + dock1[i].getShipSize());
}
}
}
private static void printWaitingList() {
System.out.println("Waiting List:");
for (int i = 0; i < waitingList.length; i++) {
if (waitingList[i] == null) {
System.out.println("Dock " + i + " is empty");
} else {
System.out.println("Dock " + i + ": " + waitingList[i].getShipName() + " " + waitingList[i].getShipSize());
}
}
}
}
The problem is that whenever a Ship is not docked at the first position (index 0) you will not check the other positions, thats because you have a break statement if it does not equal the name of the ship to be undocked. The break statement terminates the loop and does not continue to check the other positions.
Just remove the break statement in the undock method.
EDIT
Your code should be like this.
System.out.println("Status of ships: ");
printDock();
System.out.println("Enter ship's name to undock: ");
String name = scan.nextLine();
boolean deleted = false;
for (int i = 0; i < dock1.length; i++) {
if (dock1[i] != null && dock1[i].getShipName().equals(name)) { //ONLY FINDING in ARRAY 0
dock1[i] = null;
System.out.println("Ship removed");
deleted = true;
/// HERE CHECK IF SHIP IN DOCK
for (int j = 0; j < waitingList.length; j++) {
if (dock1[i] == null && waitingList[j] != null) {
// Add ship to the dock
dock1[i] = new Ship(waitingList[j].getShipName(), waitingList[j].getShipSize());
System.out.println("Move ship from waiting list to dock 1");
waitingList[j] = null;
return;
} else {
// System.out.println("No space in dock");
return;
}
}
}
}
if (!deleted) System.out.println("No ship was removed")
I see 2 mistakes:
1) You break the loop in the else statement in the undock method.
2) If you find the ship name in the first dock, then you do always return in the first iteration of the waitingList loop.
for (int i = 0; i < dock1.length; i++) {
if (dock1[i] != null && dock1[i].getShipName().equals(name)) { //ONLY FINDING in ARRAY 0
dock1[i] = null;
System.out.println("Ship removed");
/// HERE CHECK IF SHIP IN DOCK
for (int j = 0; j < waitingList.length; j++) {
if (dock1[i] == null && waitingList[j] != null) {
// Add ship to the dock
dock1[i] = new Ship(waitingList[j].getShipName(), waitingList[j].getShipSize());
System.out.println("Move ship from waiting list to dock 1");
waitingList[j] = null;
return;
} else {
// System.out.println("No space in dock");
return;
}
}
// NOTE -> THIS ALWAYS ENDS IN A RETURN
} else {
System.out.println("Ship not docked here");
break;
}
}
I think you should leave out the break statement in order to try other docks. Also, so not return to the caller method when testing the waiting list.
So try this:
for (int i = 0; i < dock1.length; i++) {
if (dock1[i] != null && dock1[i].getShipName().equals(name)) { //ONLY FINDING in ARRAY 0
dock1[i] = null;
System.out.println("Ship removed");
/// HERE CHECK IF SHIP IN DOCK
for (int j = 0; j < waitingList.length; j++) {
if (dock1[i] == null && waitingList[j] != null) {
// Add ship to the dock
dock1[i] = new Ship(waitingList[j].getShipName(), waitingList[j].getShipSize());
System.out.println("Move ship from waiting list to dock 1");
waitingList[j] = null;
return;
} else {
// System.out.println("No space in dock, go on in waiting list");
// NO RETURN HERE
}
}
} else {
System.out.println("Ship not docked here, try next dock if there is one left");
// NO BREAK HERE
}
}
System.out.println("Ship not docked in any dock");

Where to close FileWriter when reusing it in different methods?

I have encountered a problem: I need to be able to filewrite after I have added to the array (dock) and removed from the array (undock) on the fly. But I do not know where to put the flush() and close(). I get errors when I but it after the write function wherever I put them because they have already closed the filewriter. Can you help?
try {
portLog.flush();
} catch (IOException e) {
e.printStackTrace();
}
try {
portLog.close();
} catch (IOException e) {
e.printStackTrace();
}
Here is my code:
import java.io.FileWriter;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;
public class Main {
static Scanner scan = new Scanner(System.in);
private static Ship[] dock1 = new Ship[10];
private static Ship[] waitingList = new Ship[10];
static FileWriter portLog;
static DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
//get current date time with Date()
static Date date = new Date();
static {
try {
portLog = new FileWriter("\\Users\\Smith\\Desktop\\PortLog.txt", true);
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
menu();
}
public static void menu() {
Scanner scan = new Scanner(System.in);
while (true) {
System.out.println("Choose an option: 1-3");
System.out.println("1. Dock");
System.out.println("2. Undock");
System.out.println("3. Status");
int menu = scan.nextInt();
switch (menu) {
case 1:
System.out.println("1. Dock");
dock();
break;
case 2:
System.out.println("2. Undock");
undock();
break;
case 3:
System.out.println("3. Status");
printDock();
printWaitingList();
break;
case 4:
System.out.println("4. Exit");
System.exit(0);
default:
System.out.println("No such option");
break;
}
}
}
public static void dock() {
System.out.println("Enter ship's name: ");
String name = scan.nextLine();
System.out.println("Enter ship's size: ");
String size = scan.nextLine();
System.out.println("Enter the ships dock:");
//Check if the dock number is valid
int i = Integer.valueOf(scan.nextLine());
if (i >= 0 && i < 10 && dock1[i] == null) {
int c = 0;
int co = 0;
int sco = 0;
for (int j = 0; j < dock1.length; j++) {
if (dock1[j] != null && dock1[j].getShipSize().equals("Cargo")) {
c++;
}
if (dock1[j] != null && dock1[j].getShipSize().equals("Container")) {
co++;
}
if (dock1[j] != null && dock1[j].getShipSize().equals("Super-Container")) {
sco++;
}
}
if (c < 10 && co < 5 && sco < 2) {
//Add ship to the dock
dock1[i] = new Ship(name, size);
System.out.println("Enough space you can dock");
System.out.println("Ship has been docked");
try {
portLog.write("\n" + " Docked: " + dock1[i].getShipName() + " Size: " + dock1[i].getShipSize() + " at " + dateFormat.format(date));
} catch (IOException e) {
e.printStackTrace();
}
} else {
System.out.println("You cannot dock");
waitingList(name, size);
}
} else {
System.out.println("Couldn't dock");
waitingList(name, size);
}
}
public static void undock() {
System.out.println("Status of ships: ");
printDock();
System.out.println("Enter ship's name to undock: ");
String name = scan.nextLine();
for (int i = 0; i < dock1.length; i++) {
if (dock1[i] != null && dock1[i].getShipName().equals(name)) {
try {
portLog.write("\n" + "Undocked: " + dock1[i].getShipName() + " Size: " + dock1[i].getShipSize() + " at " + dateFormat.format(date));
} catch (IOException e) {
e.printStackTrace();
}
dock1[i] = null;
System.out.println("Ship removed");
/// HERE CHECK IF SHIP IN DOCK
for (int j = 0; j < waitingList.length; j++) {
if (dock1[i] == null && waitingList[j] != null) {
// Add ship to the dock
dock1[i] = new Ship(waitingList[j].getShipName(), waitingList[j].getShipSize());
System.out.println("Move ship from waiting list to dock 1");
waitingList[j] = null;
return;
} else {
return;
}
}
} else {
}
}
System.out.println("Ship not found");
}
public static void waitingList(String name, String size) {
System.out.println("Dock 1 is full, ship will try to be added to Waiting List");
for (int i = 0; i < waitingList.length; i++) {
if (waitingList[i] == null) {
//Add ship to the dock
waitingList[i] = new Ship(name, size);
System.out.println("Enough space added to waiting list");
return;
} else {
}
}
System.out.println("No space on waiting list, ship turned away.");
}
public static void printDock() {
System.out.println("Docks:");
for (int i = 0; i < dock1.length; i++) {
if (dock1[i] == null) {
System.out.println("Dock " + i + " is empty");
} else {
System.out.println("Dock " + i + ": " + dock1[i].getShipName() + " " + dock1[i].getShipSize());
}
}
}
private static void printWaitingList() {
System.out.println("Waiting List:");
for (int i = 0; i < waitingList.length; i++) {
if (waitingList[i] == null) {
System.out.println("Dock " + i + " is empty");
} else {
System.out.println("Dock " + i + ": " + waitingList[i].getShipName() + " " + waitingList[i].getShipSize());
}
}
}
}
That is the thing when you are new to Java, and first start using all static variables within a single class. That is good for the first steps, and getting a hello world printed, or some simple calculations.
But then this approach quickly gets into your way. You see, in the "real" world of OOP, such code is much more of an anti-pattern.
Meaning: that is where you should starting thinking of creating classes of your own. A class has a distinct purpose, like modelling a Ship, or maybe a Dock. Then you add think about the properties that belong into such classes (and for sure: these fields are not static) then.
In that sense, the real answer here is that you "fully" step back and start thinking about better ways to organize the functionalities that you intend to create. As said, in your case, that boils down to define proper Ship/Dock classes. That will then allow you to abstract lower level details, such as "some stuff is stored in files". Because then you can have a DockPersistenceService class for example. Which you pass a list of Dock objects, to somehow persist them. Or that reads a list of Dock objects from a file.
As a general principle, it's a good idea for a resource like this to have a well-defined lifetime. That will typically mean that it's not static. #GhostCat is right that you should really consider a more robust approach, but as a starting point, I'd suggest this.
public static void menu() {
Scanner scan = new Scanner(System.in);
boolean keepProcessing = true; // use this to control the loop, don't call System.exit!
// use try-with-resources to control resource lifetime
try (FileWriter portLog = new FileWriter("\\Users\\Smith\\Desktop\\PortLog.txt", true)) {
while (keepProcessing) {
int choice = scan.nextInt();
switch (choice) {
case 1:
System.out.println("1. Dock");
dock(portLog);
break;
// Other cases skipped for brevity
case 4:
keepProcessing = false;
break;
// Other cases skipped for brevity
}
}
}
}
Then, have your other methods accept the portLog as a parameter.
public static void dock(FileWriter portLog) {
// ...
}
With this setup, the menu method will open the portLog file when it starts up, and close it when the method is finished. It also makes it clearer that the dock, undock, etc. methods require the use of the FileWriter object.

Counting occurrence of attributes inside the objects of a Java Array

I have created an array of 25 Flower objects. Each flower object holds the flower name(String), flower color(String), presence of thorns(boolean), and flower scent(String). These attributes are handled by the 'Flower' class. I have pasted both classes in case the error is being caused by either class. The user inputs all of the attributes of the flowers when the menu prompts for the information. After the user enters all of the flowers they want to, I need to be able to print out the entire array and a counter of how many of each flower there are. For instance, if the user puts in 10 flowers and there are 3 Roses, 2 Lilly's, 3 Dandelions, and 2 Orchids, I need to print the entire array and then print the number each flower was present. The format for the display is:
Flower name: Rose Flower color: Red Flower has thorns: true Flower scent: Sweet
Rose - 3
Lilly - 3
Dandelion - 3
Orchid - 2
I am able to print out the array as shown, but cannot get the count variable to work properly. I do not need to sort this array.
Another issue I am getting in an OutOfBounds error. I can only put in 24 flowers before I encounter this error. The 25th flower triggers it. I thought this was covered by the addFlower index counter, but obviously, I was incorrect.
This assignment does not allow the use of ArrayList, which would make this much simpler. We have not explored error handling yet either.
Current code is:
package assignment2;
import java.util.Scanner;
public class Assignment2
{
public static void main(String[] args)
{
new Assignment2();
}
public Assignment2()
{
Scanner input = new Scanner(System.in);
Flower flowerPack[] = new Flower[25];
System.out.println("Welcome to my flower pack interface.");
System.out.println("Please select a number from the options below");
System.out.println("");
while (true)
{
// Give the user a list of their options
System.out.println("1: Add an item to the pack.");
System.out.println("2: Remove an item from the pack.");
System.out.println("3: Search for a flower.");
System.out.println("4: Display the flowers in the pack.");
System.out.println("0: Exit the flower pack interfact.");
// Get the user input
int userChoice = input.nextInt();
switch (userChoice)
{
case 1:
addFlower(flowerPack);
break;
case 2:
removeFlower(flowerPack);
break;
case 3:
searchFlowers(flowerPack);
break;
case 4:
displayFlowers(flowerPack);
break;
case 0:
System.out.println("Thank you for using the flower pack interface. See you again soon!");
input.close();
System.exit(0);
}
}
}
private void addFlower(Flower flowerPack[])
{
String flowerName; // Type of flower
String flowerColor; // Color of the flower
Boolean hasThorns = false; // Have thorns?
String flowerScent; // Smell of the flower
int index = 0;
Scanner input = new Scanner(System.in);
System.out.println("What is the name of flower is it?");
flowerName = input.nextLine();
System.out.println("What color is the flower?");
flowerColor = input.nextLine();
System.out.println("Does the flower have thorns?");
System.out.println("Choose 1 for yes, 2 for no");
int thorns = input.nextInt();
if(thorns == 1)
{
hasThorns = true;
}
input.nextLine();
System.out.println("What scent does the flower have?");
flowerScent = input.nextLine();
Flower fl1 = new Flower(flowerName, flowerColor, hasThorns, flowerScent);
for(int i = 0; i < flowerPack.length; i++)
{
if(flowerPack[i] != null)
{
index++;
if(index == flowerPack.length)
{
System.out.println("The pack is full");
}
}
else
{
flowerPack[i] = fl1;
break;
}
}
}
private void removeFlower(Flower flowerPack[])
{
Scanner input = new Scanner(System.in);
System.out.println("What student do you want to remove?");
displayFlowers(flowerPack);
System.out.println("Choose 1 for the first flower, 2 for the second, etc" );
int index = input.nextInt();
index = index - 1;
for (int i = 0; i < flowerPack.length - 1; i++)
{
if(flowerPack[i] != null && flowerPack[i].equals(flowerPack[index]))
{
flowerPack[i] = flowerPack[i + 1];
}
}
}
private void searchFlowers(Flower flowerPack[])
{
Scanner input = new Scanner(System.in);
String name;
System.out.println("What flower would you like to search for?");
name = input.nextLine();
boolean found = false;
for (int i = 0; i < flowerPack.length; i++)
{
if (flowerPack[i].getFlowerName().equalsIgnoreCase(name))
{
found = true;
break;
}
}
if (found)
{
System.out.println("We found your flower.");
}
else
{
System.out.println("That flower was not found.");
}
}
private void displayFlowers(Flower flowerPack[])
{
int count = 1;
for(int i = 0; i < flowerPack.length; i++)
{
if (flowerPack[i] != null)
{
if (flowerPack[i].equals(flowerPack[i+1]))
{
count++;
}
else
{
System.out.println(flowerPack[i]);
count = 1;
}
}
else
{
if (flowerPack[i] == null)
{
break;
}
}
}
}
}
The Flower class is below.
package assignment2;
public class Flower
{
#Override
public String toString()
{
return "Flower name: " + this.getFlowerName() + "\t" +
"Flower color: " + this.getFlowerColor() + "\t" +
"Flower has thorns: " + this.getHasThorns() + "\t" +
"Flower scent: " + this.getFlowerScent() + "\t" ;
}
private String flowerName;
private String flowerColor;
private Boolean hasThorns;
private String flowerScent;
Flower(String flowerName, String flowerColor, Boolean hasThorns, String flowerScent)
{
this.flowerName = flowerName;
this.flowerColor = flowerColor;
this.hasThorns = hasThorns;
this.flowerScent = flowerScent;
}
String getFlowerName()
{
return flowerName;
}
private void setFlowerName(String flowerName)
{
this.flowerName = flowerName;
}
private String getFlowerColor()
{
return flowerColor;
}
private void setFlowerColor()
{
this.flowerColor = flowerColor;
}
private Boolean getHasThorns()
{
return hasThorns;
}
private void setHasThorns()
{
this.hasThorns = hasThorns;
}
private String getFlowerScent()
{
return flowerScent;
}
private void setFlowerScent()
{
this.flowerScent = flowerScent;
}
}
private void displayFlowers(Flower flowerPack[])
{
String[] usedNames = new String[flowerPack.length];
int[] nameCounts = new int[flowerPack.length];
int usedNamesCount = 0;
for (int i = 0; i < flowerPack.length; i++)
{
Flower flower = flowerPack[i];
if (flower == null)
{
continue;
}
int nameIndex = -1;
for (int j = 0; j < usedNamesCount; j++)
{
String usedName = usedNames[j];
if (flower.getFlowerName().equals(usedName))
{
nameIndex = j;
break;
}
}
if (nameIndex != -1)
{
nameCounts[nameIndex] += 1;
}
else
{
usedNames[usedNamesCount] = flower.getFlowerName();
nameCounts[usedNamesCount] += 1;
usedNamesCount++;
}
}
for (int i = 0; i < usedNamesCount; i++)
{
System.out.println(usedNames[i] + "s - " + nameCounts[i]);
}
}

fill two dimensionell boolean array

I need to fill a boolean array one by one. Here is the code I have for filling the first row to true, one by one and it's working. I want to do this with a loop or something so I don't need all the if, else if statements. Any suggestions of how to do that?
public class Airline {
boolean seat[][] = new boolean[2][3];
Scanner input = new Scanner(System.in);
public void start() {
while (true) {
makeReservation();
}
}
public void makeReservation() {
System.out.println("Press 1 or 2");
int klass = input.nextInt();
if (klass == 1) {
firstClassSeat();
} else {
economySeat();
}
}
public void firstClassSeat() // assign a first class seat
{
for (int row = 0; row < seat.length; row++) {
for (int col = 0; col < seat[row].length; col++) {
}
if (seat[0][0] == false)
{
seat[0][0] = true; // assign seat
System.out.println("You now have seat 00 in first class");
break;
}
if (seat[0][1] == false) {
seat[0][1] = true; // assign seat
System.out.println("You now have seat 01 in first class");
break;
} else if (seat[0][2] == false) {
seat[0][2] = true; // assign seat
System.out.println("You now have seat 02 in first class");
break;
} else {
System.out.println("The plane is full");
int val = input.nextInt();
if (val == 1) {
economySeat();
start();
} else {
System.out.println("Thank you and welcome again");
System.exit(0);
}
}
}
}
public void economySeat() // assign an economy seat
{
for (int row = 0; row < seat.length; row++) {
for (int col = 0; col < seat[row].length; col++) {
}
if (seat[1][0] == false)
{
seat[1][0] = true; // assign seat
System.out.println("You now have seat 01 in first class");
break;
}
if (seat[1][1] == false) {
seat[1][1] = true; // assign seat
System.out.println("You now have seat 02 in first class");
break;
} else if (seat[1][2] == false) {
seat[1][2] = true; // assign seat
System.out.println("You now have seat 02 in first class");
break;
} else {
System.out.println("The economy class is full ");
int val = input.nextInt();
if (val == 1) {
economySeat();
start();
} else {
System.out.println("Thank you and welcome again");
System.exit(0);
}
}
}
}
}
Here's what I did with the firstclass method
public void firstClassSeat() {
for (int row = 0; row < seat.length; row++) {
for (int col = 0; col < seat[row].length; col++) {
if (!seat[row][col])
{
seat[row][col] = true;
System.out.println("You have place number 0" + row + " in the Firstclass");
break;
} else if (seat[0][2]) {
if (seat[1][2]) {
System.out.println("The plane is full, welcome again");
System.exit(0);
}
} else {
System.out.println("First class is full. Economyclass? 1 for yes 2 for no");
int choice = input.nextInt();
if (choice == 1) {
economySeat();
start();
} else {
System.out.println("Thank you and welcome again");
System.exit(0);
}
}
}
}
}
But I don't know how to do so it only makes the array true one by one. This code takes two at the time. Any suggestions?
There are a lot of very bad conventions in your code, but what you're looking for is
for(int i = 0; i < seat.length; i++)
for(int j = 0; j < seat[i].length; j++)
seat[i][j] = newBool;

Categories

Resources