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
Related
I am trying to do a basic Java Airline Reservation App. Here is my code, It seems that after I press '1' it is terminating and not running the rest of the code. I am not sure if it is something wrong with my loop or why it is terminating. Please if anyone has any ideas or answers I would love to hear them! thanks
import java.util.Scanner;
public class Reservation {
boolean[] seat = new boolean[11];
Scanner input = new Scanner(System.in);
public void start() {
while (true) {
makeReservation();
}
}
public void makeReservation() {
System.out.println("Please type 1 for first class and type 2 for economy");
int section = input.nextInt();
if (section == 1) {
firstClassSeat();
} else {
economySeat();
}
}
public void firstClassSeat() {
for (int count = 1; count <= 5; count++) {
if (seat[count] = false) {
seat[count] = true;
System.out.printf("First Class. Seat# %d\n", count);
break;
} else if (seat[10] == true) {
if (seat[5] == true) {
} else {
System.out.println("First class is fully booked, would you like an econmy seat");
int choice = input.nextInt();
if (choice == 1) {
firstClassSeat();
start();
} else {
System.out.println("Next flight is in 3 hours");
System.exit(0);
}
}
}
}
}
public void economySeat() {
for (int count = 6; count <= 10; count++) {
if (seat[count] = false) {
seat[count] = true;
System.out.printf("First Class. Seat# %d\n", count);
break;
} else if (seat[10] == true) {
if (seat[5] == true) {
} else {
System.out.println("Economy is fully booked. Would you like First Class? 1 for Yes 2 for No");
int choice = input.nextInt();
if (choice == 1) {
firstClassSeat();
start();
} else {
System.out.println("Next flight is in 3 hours");
System.exit(0);
}
}
}
}
}
}
First off, there is no need to compare booleans inside an if. seats[i] == false is the same as !seats[i].
Nothing is happening because you have an assignment:if(seat[count]=false instead of comparison:if(seat[count]==false. That's the first error, after fixing that you will start assigning seats.
Next, you're calling firstClassSeat inside the same method, when I think you wanted to call economySeat (when first class is full). You need to fix the logic behind the checks and economy/first class suggestions.
import java.util.*;
/**
* Write a description of class TheaterApp here.
*
* #author (your name)
* #version (a version number or a date)
*/
public class TheaterApp {
static int [][] seats = {
{10,10,10,10,10,10,10,10},
{10,10,10,10,10,10,10,10},
{10,10,20,20,20,20,10,10},
{20,20,30,30,30,30,20,20},
{30,30,40,40,40,40,30,30},
{30,40,40,50,50,40,40,40}};
/**
* Constructor for objects of class TheaterApp
*/
public static void main(String [] args)
{
Scanner input = new Scanner(System.in);
String ans;
do {
System.out.print("Enter request, please (or 'help' or 'quit') ");
ans = input.next();
if (ans.equals("help")) {
System.out.println("Possible commands");
System.out.println("price <price>");
System.out.println("seat <row> <seat>");
System.out.println("left");
System.out.println("remaining <price>");
System.out.println("print");
System.out.println("quit");
System.out.println("help");
} else if (ans.equals("price")) {
int p = input.nextInt();
for (int i = 0; i < seats.length; i++) {
for (int j = 0; j < seats[i].length; j++) {
if (seats[i][j] == 0) {
System.out.println("Next available seat at position: " + i + " " + j);
}
}
}
// Find the 'best' seat at the given price
} else if (ans.equals("seat")) {
int r = input.nextInt();
int c = input.nextInt();
int k;
int i;
int j;
for (int l = 0; l < 6; l++) {
k = 1;
for(i=0;i<6;i++) {
for(j=0;j<8;j++) {
if (k == input.nextInt()) {
// check if the seat has already been reserved
if (seats[i][j]== 0) {
System.out.println("That seat has already been reserved");
}
// if its not reserved then reserve it
else {
seats[i][j]= 0;
}
}
k++;
System.out.println(seats[i][j]);
}
}
}
// Reserve the given row and seat, if possible
} else if (ans.equals("left")) {
// Print the total available seats
} else if (ans.equals("remaining")) {
int p = input.nextInt();
// Print the total available seats at this price
} else if (ans.equals("print")) {
for (int r = 0; r < seats.length; ++r) {
for (int s = 0; s < seats[r].length; ++s) {
System.out.print(seats[r][s] + " ");
}
System.out.println();
}
} else if (!ans.equals("quit")) {
System.out.println("Come again?");
}
} while (!ans.equals("quit"));
System.out.println("Good bye");
}
}
This array represents theater seats and I have to mark sold seats by changing the price to 0. I also have to make sure seats are open when a user asks for a a certain spot, and when a user enters a price, find any seats that are open.
So I'm pretty sure I figured out the code for finding the best seat at any given price. I can't figure out how to do the remaining code.
I just need to find out how to print the total available seats and also how to print the total available seats when a certain price is entered.
Thanks.
You'd just use nested for loops, like you did before, except now you'd have some kind of a availableSeats counter you'll increment every time a seat meets a certain condition.
Like so:
int availableSeats = 0;
for(i=0;i<6;i++) {
for(j=0;j<8;j++) {
if(seats[i][j] == sometargetprice){
availableSeats++;
}
}
}
System.out.println("Total of " + availableSeats + " are available.");
Unless I'm not understanding the problem correctly.
Can someone edit my code to make it loop the selection menu. If the choice is not one of the 5 options it will prompt the user to re-enter until it is a valid option. If possible an explanation would be helpful as well. Thanks
Here is my code.
import java.util.*;
public class ShapeLoopValidation
{
public static void main (String [] args)
{
chooseShape();
}
public static void chooseShape()
{
while (true){
Scanner sc = new Scanner(System.in);
System.out.println("Select a shape number to calculate area of that shape!");
System.out.print("Circle = 1. \nRectangle = 2. \nTriangle = 3. \nExit = 4. \nINPUT : ");
int shapeChoice = sc.nextInt();
//while (true) {
if (shapeChoice >= 1 && shapeChoice <=4)
{
if (shapeChoice == 1)
{
circle();
}
else if (shapeChoice == 2)
{
rectangle();
}
else if (shapeChoice == 3)
{
triangle();
}
else if (shapeChoice == 4)
{
return;
}
}
else
{
System.out.print("Error : Choice " + shapeChoice + "Does not exist.");
}
}
class Test {
int a, b;
Test(int a, int b) {
this.a = a;
this.b = b;
}
}
}
First: take a look at switch
Second: read a bit about do-while loops (they are usually a good fit for this kind of situations).
Now, how I would implement it (but you should really learn how to make a loop in this scenarios):
public static void chooseShape () {
boolean valid = false;
do {
Scanner sc = new Scanner(System.in);
System.out.println("Select a shape number to calculate area of that shape!");
System.out.print("Circle = 1. \nRectangle = 2. \nTriangle = 3. \nExit = 4. \nINPUT : ");
int shapeChoice = sc.nextInt();
switch (shapeChoice) {
valid = true;
case 1:
circle();
break;
case 2:
rectangle();
break;
case 3:
triangle();
break;
case 4:
return;
default:
valid = false;
System.out.println("Error : Choice " + shapeChoice + "Does not exist.");
System.out.println("Please select one that exists.")
}
} while (!valid)
}
Use do-while flow control until EXIT code entered:
int shapeChoice;
do {
System.out.println("Select a shape number to calculate area of that shape!");
System.out.print("Circle = 1. \nRectangle = 2. \nTriangle = 3. \nExit = 4. \nINPUT : ");
int shapeChoice = sc.nextInt();
// then use if-else or switch
} while (shapeChoice != 4);
OR
use break statement to loop break at your code as bellow:
else if (shapeChoice == 4)
{
break;
}
I have a main menu class which gets a choice from the user and then uses that choice to select other classes from a switch statement pertaining to the menu options. My code is:
public static void main(String[] args) {
int dieOne = 0;
int dieTwo = 0;
int choice = 0;
DiceMaker dice = new DiceMaker(); // class that creates the dice
RollDice roll = new RollDice(); // class that imitates roll
DiceMenu menu = new DiceMenu();
DiceRoller series = new DiceRoller();
System.out.println("Welcome to the Dice Roll Stats Calculator!\n");
while (choice != 4) {
menu.DiceMenu();
choice = menu.getUserChoice();
switch (choice) {
case 1:
dice.diceMaker();
dieOne = dice.DieOne();
dieTwo = dice.DieTwo();
System.out.println(dice.DieOne() + dice.DieTwo());
return;
case 2:
roll.rollDice(dieOne, dieTwo);
roll.displayRoll();
return;
case 3:
series.diceRoller();
series.displayResults();
return;
case 4:
break;
}// switch (choice)
} // while (choice != 4)
}
Case for is the 'Exit' option, so I put the switch statement in a while loop with the boolean condition being not equal to 4 so that when the choice was set to 4 the loop would stop. The proper case executes but the problem I'm having is that the loop, and consequently the program stop after each case that I try, even if the choice was not 4. I tried using break statements after case 1, 2 and 3 as well, and when I did that, it would just repeat the case in an infinite loop. I tried to figure this out on my own cut could never find anything that resembled what I was seeing enough for me to figure out what the problem was. I'm guessing this probably isn't the best way to make a menu in the future. Thank in advance.
The rest of my code is as follows. Please note, DiceRoller class is still under construction, but DiceMaker and RollDice classes seem to be working.
DiceMenu class:
public class DiceMenu
{
public static final int CHOICE_UNKNOWN = 0;
public static final int CHOICE_MAKE_DICE = 1;
public static final int CHOICE_ROLL_ONCE = 2;
public static final int CHOICE_SERIES_ROLL = 3;
public static final int CHOICE_QUIT = 4;
private int choice = 0;
Scanner scan = new Scanner(System.in);
public int DiceMenu()
{
while ( this.choice < 1 || this.choice > 4 ) // while loop keeps choices in range
{
System.out.println(" MAIN MENU\n");
System.out.println("1. Create Your Dice");
System.out.println("2. Roll Your Dice");
System.out.println("3. Perform A Series Of Rolls And Show Stats");
System.out.println("4. Exit\n");
try // avoid invalid input
{
System.out.print("Please choose an option: ");
this.choice = scan.nextInt(); // get number of sides from user
}
catch (InputMismatchException e)
{
//if input is invalid, returns to beginning of loop
System.out.println("Invalid Input. Please try again.\n");
scan.next();
continue;
}
if ( this.choice < 1 || this.choice > 4 ) // if input is out of range
// notify user before continuing
{
System.out.println("Choice must reflect menu options. (1-4)"
+ " Please try again.\n");
this.choice = 0;
}
}//while ( this.choice < 1 || this.choice > 4 )
return 0;
}
public int getUserChoice()
{
return this.choice;
}
}
RollDice class:
public class RollDice
{
private int roll;
private int rollOne;
private int rollTwo;
private int rollTotal;
public int rollDice (int dieOne, int dieTwo)
{
this.rollOne = 1 + (int)(Math.random() * dieOne);
this.rollTwo = 1 + (int)(Math.random() * dieTwo);
this.rollTotal = this.rollOne + this.rollTwo;
return 0;
}
public void displayRoll()
{
System.out.println("You roll a " + rollOne + " and a "
+ rollTwo + " for a total of " +
rollTotal + "!"); //display separate and total
//roll amounts
if ( rollTotal == 2 ) // if/else tests for special rolls
{
System.out.println("Snake Eyes!");
}
else if ( rollTotal == 7 )
{
System.out.println("Craps!");
}
else if ( rollOne == 6 && rollTwo == 6 )
{
System.out.println("Boxcars!");
}
}
}// public class DiceRoller
DiceMaker class:
public class DiceMaker
{
private int sides = 0;
private int dieOne;
private int dieTwo;
public int diceMaker()
{
while ( sides < 4 || sides > 20 ) // while loop keeps sides within range
{
Scanner scan = new Scanner(System.in);
try // avoid invalid input
{
System.out.print("Please enter the number of sides each die "
+ "should have (must be between 4 and 20): ");
this.sides = scan.nextInt(); // get number of sides from user
}
catch (InputMismatchException e)
{
//if input is invalid, returns to beginning of loop
System.out.println("Invalid Input. Please try again.\n");
scan.next();
continue;
}
if (sides < 4 || sides > 20) // if input is out of range
// notify user before continuing
{
System.out.println("Die must have between 4 and 20 sides."
+ " Please try again.\n");
}
}//while ( sides < 4 || sides > 20 )
this.dieOne = sides;
this.dieTwo = sides;
return 0;
}
public int DieOne()
{
return this.dieOne;
}
public int DieTwo()
{
return this.dieTwo;
}
}// public class DiceMaker
Remove the return(s) from cases 1,2 and 3. If you return from main the program terminates. You want to loop so don't do that. However, as pointed out by #ajb in the comments below, you don't want the case(s) to fall through. So you need break(s).
case 1: dice.diceMaker();
dieOne = dice.DieOne();
dieTwo = dice.DieTwo();
System.out.println(dieOne + dieTwo);
// return;
break; // <-- applies to innermost block (switch).
case 2: roll.rollDice(dieOne, dieTwo);
roll.displayRoll();
// return;
break; // <-- applies to innermost block (switch).
case 3: series.diceRoller();
series.displayResults();
// return;
break; // <-- applies to innermost block (switch).
Also, you could use continue (here, which would apply to the innermost loop). Finally, remember that case 4 terminates the loop (because choice is 4) and you don't need case 4 for that reason.
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;