fill two dimensionell boolean array - java

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;

Related

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");

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

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;

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]);
}
}

Java_Fill an array by getters

Trying to fill an array using getter, the problem the array is full with the same number and if the value change in the second input the hole array changes again :
public class Payment {
Scanner kb = new Scanner(System.in);
private int operationNum = 0;
private int subOperationNum = 0;
private double reMoney = 0;
public int getOperationNum() {
return operationNum;
}
public int getSubOperationNum() {
return subOperationNum;
}
public double getReMoney() {
return reMoney;
}
public void setOperationNum(int operationNum) {
this.operationNum = operationNum;
}
public void setSubOperationNum(int subOperationNum) {
this.subOperationNum = subOperationNum;
}
public void setReMoney(double reMoney) {
this.reMoney = reMoney;
}
public void operationsLoop() {
double [] a = new double[17];
do {
System.out.println("\n1- Cash");
System.out.println("2- Car");
System.out.println("3- Clothing");
System.out.println("4- Credit Card");
System.out.println("5- Food");
System.out.println("6- Education");
System.out.println("7- Electronics");
System.out.println("8- Groceries");
System.out.println("9- Health & Fitness");
System.out.println("10- Medical");
System.out.println("11- Travel");
System.out.println("12- Utilities");
System.out.println("13- Finish");
System.out.print("\nEnter the number of operation : ");
this.setOperationNum(kb.nextInt());
this.operation2();
this.operation12();
this.collectReMoney();
**for(int i = 0; i<a.length;i++){
a[i] = this.getReMoney();
System.out.print(a[i] + ", ");
}**
} while (operationNum < 13);
}
public void operation2() {
if (this.getOperationNum() == 2) {
System.out.println("\t1- Gas");
System.out.println("\t2- Repair");
System.out.println("\t3- Monthly Payment");
System.out.print("\nEnter your chose : ");
this.setSubOperationNum(kb.nextInt());
}
}
public void operation12() {
if (this.getOperationNum() == 12) {
System.out.println("\t1- Electricity");
System.out.println("\t2- Gas");
System.out.println("\t3- Telephone");
System.out.println("\t4- Water");
System.out.print("\nEnter your chose : ");
this.setSubOperationNum(kb.nextInt());
}
}
public void collectReMoney() {
if (this.getOperationNum() == 1) {
System.out.print("Withdraw = ");
this.setReMoney(kb.nextDouble());
} else if (this.getOperationNum() == 4 || (this.getOperationNum() == 2 && this.getSubOperationNum() == 3)) {
System.out.print("Payment = ");
this.setReMoney(kb.nextDouble());
} else if (this.getOperationNum() == 9 || this.getOperationNum() == 10) {
System.out.print("Pay = ");
this.setReMoney(kb.nextDouble());
} else if (this.getOperationNum() != 13) {
System.out.print("Spend = ");
this.setReMoney(kb.nextDouble());
}
}
and if I add to the array loop "this.setReMoney(0);" only the first value change
when the user enter a value i want to insert it in the array according to the operation number and the rest values of the other operations should be zero
In the for loop you are assigning the same number to each of the elements of the array, to avoid that you should take the assigning operation outside the for loop:
a[operationNum - 1] = this.getReMoney();
for(int i = 0; i<a.length;i++){
System.out.print(a[i] + ", ");
}
Also, make sure that you check for ArrayIndexOutOfBoundsException in the case the user selects an option number grater than the size of the array.

Unknown NullPointerException

I'm writing a simple class to simulate an airplane reservation system. Unfortunately, I keep having my plan-to-hog-all-first-class-seats glee interrupted by multiple null pointer exceptions, and I can't find them anywhere. Here is my completed work:
import java.util.*;
public class airplane
{
boolean[] seats;
Scanner scan = new Scanner(System.in);
public airplane(int num_of_seats)
{
boolean[] seats = new boolean[num_of_seats];
for (int counter = 0; counter < num_of_seats; counter++)
{
seats[counter] = true;
}
}
public boolean seatFirstClass(int seat)
{
if ( seat <= seats.length / 4 )
return true;
else
return false;
}
public void seatsReserveFirstClass()
{
for (int seat = 0; seat < seats.length; seat++)
{
if (seats[seat] == true && seat <= seats.length / 4)
{
seats[seat] = false;
System.out.print("I have reserved one seat in first class. Please tell the passenger to enjoy their flight with these airlines! ");
break;
}
}
System.out.print("I could not find a seat in first class. Can the passenger switch to economy? (0 for no, 1 for yes) ");
int choice = scan.nextInt();
if (choice == 0)
System.out.print("I could not add passenger due to lack of a seat.");
else if (choice == 1)
{
this.seatsReserveEconomy();
}
}
public void seatsReserveEconomy()
{
for (int seat = 0; seat < seats.length; seat++)
{
if (seats[seat] == true && seat > seats.length / 4)
{
seats[seat] = false;
System.out.print("I have reserved a seat in economy. Please tell the passenger to enjoy their flight with these airlines! ");
break;
}
}
System.out.print("I could not find a seat in economy. Can the passenger switch to first class? (0 for no, 1 for yes) ");
int choice = scan.nextInt();
if (choice == 0)
System.out.print("I could not add the passenger due to a lack of seats.");
else if (choice == 1)
this.seatsReserveFirstClass();
}
public void planeClear()
{
for (int seat = 0; seat < seats.length; seat++)
{
seats[seat] = true;
}
}
public void seatUnReserve(int seat)
{
if (seat < seats.length)
{
if (seats[seat] == false)
{
seats[seat] = true;
System.out.printf("Seat %d has been unreserved.\n", seat);
}
else
{
System.out.print("The seat you have entered is already unreserved.\n");
}
}
else
{
System.out.printf("There is no seat number %d on this plane.\n", seat);
}
}
}
and here is a main class to test it:
public class Test
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
boolean check = false;
System.out.print("How many seats does the plane have? ");
int num_of_seats = scan.nextInt();
airplane Airplane = new airplane(num_of_seats);
while (check == false)
{
System.out.print("Please enter 0 to reserve a first class seat, 1 to reserve an economy seat,\n2 to cancel a reservation, 3 to clear the plane,\nand 4 to quit the program. ");
int choice = scan.nextInt();
switch(choice)
{
case 0:
Airplane.seatsReserveFirstClass();
break;
case 1:
Airplane.seatsReserveEconomy();
break;
case 2:
System.out.print("Which seat should I unreserve? ");
int seat = scan.nextInt();
Airplane.seatUnReserve(seat);
break;
case 3:
Airplane.planeClear();
break;
case 4:
check = true;
break;
}
}
}
}
If this is run, the dreaded NullPointException error shows up, and I'm not sure what calls this beast.
Exception in thread "main" java.lang.NullPointerException
at airplane.seatsReserveFirstClass(airplane.java:22)
at Test.main(Test.java:15)
this is a field member:
boolean[] seats;
Scanner scan = new Scanner(System.in);
public airplane(int num_of_seats)
{
here you shadow the field member with a local variable, you are not touching the other one
boolean[] seats = new boolean[num_of_seats];
for (int counter = 0; counter < num_of_seats; counter++)
{
seats[counter] = true;
}
}
it should look like this:
public airplane(int num_of_seats)
{
seats = new boolean[num_of_seats];
for (int counter = 0; counter < num_of_seats; counter++)
{
seats[counter] = true;
}
}
Herman's quick eye found answer for you allready!! Anyway I extend the help for future...
You can use Java IDE , eclipse is good one, to develop programs. One of the very important feature, I believe, is debugging, which enables you to completely control your application and trace exception quickly.
Here is quick tutorial how to debug an application from eclipse ( Refer 4.3 for Exception breakpoints)
http://www.vogella.com/articles/EclipseDebugging/article.html

Categories

Resources