Adding two loops to an elevator system? - java

So I'm creating an elevator system to go with another piece of code. The system currently works fine, however I would like to add a while loop, so that when an invalid floor is selected, I am given the chance to retry another floor at this point in the code;
public static void selectFloor() {
Scanner scnr = new Scanner(System.in);
int newFloor;
System.out.println("Enter your destination floor >>> ");
newFloor = scnr.nextInt();
if (newFloor > 7 || newFloor < 0) {
System.out.println("Invalid floor entry");
}
I also wanted to add another loop to the system so that once a floor has been selected and the elevator arrives at the destination floor, the cycle will allow the user to select another destination from the current floor in a never ending cycle. Here is the remainder of the code;
else {
int direction = 0;
if(currentFloor < newFloor){
direction = 1;
} else if (currentFloor > newFloor) {
direction = -1; ;
} else {
direction = 0;
}
for (; currentFloor != newFloor; currentFloor += direction)
System.out.println("..." + currentFloor);
System.out.println("Elevator has arrived!");
}
}
public void fireAlarm() {
System.out.println("***FIRE ALARM*** Please exit the building safely.");
}
}
Due to the structure of my code, I can't figure out how to do this. How could I add these two loops?

You obviously need one loop that will loop forever until a break signal from keyboard input is sent (let's say that is number -1)
public static void selectFloor() {
Scanner scnr = new Scanner(System.in);
int newFloor= 0; //initalize to 0
while (newFloor != -1) { //loop forever until user gives -1 as input
System.out.println("Enter your destination floor >>> ");
System.out.println("To exit the programm enter: -1"); //tell the user how to exit
newFloor = scnr.nextInt();
if (newFloor > 7 || newFloor < 0) {
//if logic
} else {
//else logic
}
}
}

You may try it this way:
Scanner scnr = new Scanner(System.in);
int newFloor;
while (true) {
System.out.print("Enter your destination floor >>> ");
newFloor = scnr.nextInt();
if (newFloor >= 0 && newFloor <= 7) break;
System.out.println("Invalid floor entry");
};
int direction = Math.signum(newFloor - currentFloor);
while (currentFloor != newFloor) {
currentFloor += direction;
System.out.println("..." + currentFloor);
}
System.out.println("Elevator has arrived!"); }

This is my approach. I broke the whole interaction up into three methods: The first "tells the story". The second handles the input of the new floor and the third takes the elevator to the destination floor. Thus each method has a clear responsibility and can be altered at a later stage if needs be.
// Handles the whole thing
public static void elevatorAction() {
int currentFloor = 1;
int destinationFloor;
while(true) {
destinationFloor = selectNewFloor();
goToDestinationFloor(currentFloor, destinationFloor);
System.out.println("The elevator has arrived");
currentFloor = destinationFloor;
}
}
// Handles the traveling
public static void goToDestinationFloor(int currentFloor, int destinationFloor) {
int increment;
if(currentFloor == destinationFloor) {
return;
}
increment = (currentFloor < destinationFloor? 1: -1);
while(currentFloor != destinationFloor) {
currentFloor += increment;
System.out.println("..." + currentFloor);
}
}
// Lets the user select a new destination floor for the elevator
public static int selectNewFloor() {
Scanner scnr = new Scanner(System.in);
int tempNewFloor;
System.out.println("Please choose your destination floor.");
while((true) {
tempNewFloor = scnr.nextInt();
if(tempNewFloor < 0 || tempNewFloor > 7) {
System.out.println("Next floor: " + tempNewFloor);
break;
} else {
System.out.println("Invalid input: Please choose a floor between 1 and 7");
}
}
}

Related

I'm trying to add components relating to bets to my game in Java, but the program stops working after it asks for a bet amount

So I'm trying to make this car racing game, modeled after horse races. I've tested the game without the betting component and it works the way I want it to, so thats no problem. But once I started to implement the betting, the program kinda gave up on me. After the user is prompted to enter the bet, the program is just blank.
I'm not getting any error messages and I've tried debugging, but I just really can't figure it out.
I've attached the whole code minus the header; all it is is the names of the cars. (1,2,3)
public static void main(String[]args)throws IOException, InterruptedException{ //start main
Scanner in;
in = new Scanner(System.in);
boolean doAnother = true;
printHeader();
printGame();
while (doAnother) { //start while
int response;
System.out.print("\nWanna play again? 1 = yes, 2 = no.");
response = in.nextInt();
if (response == 1) { // start if loop
doAnother = true;
printHeader();
printGame();
} // end if loop
else {
doAnother = false;
System.out.println("Come back again soon!");
}
} //end while look
} //end main
public static boolean printGame()throws IOException, InterruptedException{
Scanner in = new Scanner(System.in);
Random rd = new Random();
int car = in.nextInt();
if (car >= 4) {
System.out.println("THATS NOT AN OPTION! You automatically lose.");
} else
bet();
System.out.println("Commence race!");
Thread.sleep(250);
int lambo = 0,
nissan = 0,
egg = 0;
int track = 100;
while (true) {
for (int i = 0; i < 50; i++)
System.out.println();
for (int i = 0; i < track; i++) {
System.out.print("-");
}
System.out.println();
lambo = lambo + rd.nextInt(4) + rd.nextInt(2) - rd.nextInt(2);
nissan = nissan + rd.nextInt(4) + rd.nextInt(2) - rd.nextInt(2);
egg = egg + rd.nextInt(4) + rd.nextInt(2) - rd.nextInt(2);
for (int i = 0; i < lambo; i++) //L
{
System.out.print("."); //distance travelled
}
System.out.println("ℾ");
//
for (int i = 0; i < nissan; i++) //M
{
System.out.print("."); //distance travelled
}
System.out.println("ℿ");
//
for (int i = 0; i < egg; i++) //T
{
System.out.print("."); //distance travelled
}
System.out.println("⅀");
//
for (int i = 0; i < track; i++) {
System.out.print("-");
}
System.out.println();
//
Thread.sleep(250);
//
if (nissan > track || lambo > track || egg > track) {
break;
}
}
if (car == track) {
System.out.println("\nYour car won! Rad!");
return true;
} else {
System.out.println("\nYour car lost... bummer.");
return false;
}
} //printGame
public static void bet()throws IOException, InterruptedException{
Scanner in;
in = new Scanner(System.in);
int money;
int bet;
boolean userWins = true;
money = 100;
while (true) {
System.out.println("You have " + money + " dollars.");
do {
System.out.println("How much do you wanna bet? Or, enter 0 to walk away.)");
System.out.print("$");
bet = in.nextInt();
if (bet < 0 || bet > money) {
System.out.println("Your bet must be between 0 and " + money + '.');
}
} while (bet < 0 || bet > money);{
if (bet == 0) {
System.out.println("Bye.");
break; //walk away
} else {
userWins = printGame();
}
if (userWins == true) {
money = money + bet;
}
if (userWins == false) {
money = money - bet;
System.out.println();
}
if (money == 0) {
System.out.println("Aw shoot, looks like you've are out of money!");
break;
}
}
}
System.out.println();
System.out.println("You walk away with $" + money + '.');
} //end method
You can't have two scanners nested like that. You must use the same scanner from the main method in you other methods or close that scanner

Multiple of an Integer inside range

I am doing a school project and I kinda got blocked.
I am looking forward building a javascript that asks the user of a number between 1 and 20 and then finds and lists all the multiples of that number inside range 0 and 100.
Here is what it looks like at the moment:
public static void main(String[] args) {
Scanner lector = new Scanner(System.in);
System.out.println("*** Program start ***\n");
System.out.println("Insert number [integer, between 1 and 20]: ");
boolean okay = false;
while (!okay) {
int n1 = lector.nextInt();
lector.nextLine();
if (n1<1 || n1>20) {
System.out.print("Invalid number!\nplease try again [between 1 and 20]: ");
} else {
okay = true;
System.out.println("Number accepted!");
}
int i = 0;
while (i <= 100) {
System.out.println(i);
if ((n1%100) == 0) {
System.out.println(n1);
}
i = i + 1;
}
System.out.println("\n*** End ***");
}
}
}
I am obviously bad at math cause I can't get the formula to work.
Thank you in advance!
public static void main(String[] args) {
Scanner lector = new Scanner(System.in);
System.out.println("*** Program start ***\n");
System.out.println("Insert number [integer, between 1 and 20]: ");
boolean okay = false;
while (!okay) {
int n1 = lector.nextInt();
lector.nextLine();
if (n1<1 || n1>20) {
System.out.print("Invalid number!\nplease try again [between 1 and 20]: ");
} else {
okay = true;
System.out.println("Number accepted!");
}
int i = 0;
while (i <= 100) {
System.out.println(i);
if ((n1%i) == 0) {
System.out.println(i);
}
i = i + 1;
}
System.out.println("\n*** End ***");
}
}
}
All multiples that fall between 0 and 100? That's the kind of thing for-loops are made for. After performing your IO and reading the number n1, change that while loop to the following.
for (int i = n1; i >= 0 && i <= 100; i = i + n1) {
System.out.println(i);
}
In case you aren't familiar with for loops, this basically says, set i to the value of n1, and keep adding n1 to it, printing each value as you go. When it leaves the range of 0..100, it terminates. So for instance, if 8 is entered it goes 8, 16, 24, 32, ..., 80, 88, 96.
If you really want to use a while loop, then try:
int i = n1;
while(i >= 0 && i <= 100) {
System.out.println(i);
i = i + n1;
}
public static void main(String[] args) {
Scanner lector = new Scanner(System.in);
System.out.println("*** Program start ***\n");
System.out.println("Insert number [integer, between 1 and 20]: ");
boolean okay = false;
while (!okay) {
int n1 = lector.nextInt();
lector.nextLine();
if (n1<1 || n1>20) {
System.out.print("Invalid number!\nplease try again [between 1 and 20]: ");
} else {
okay = true;
System.out.println("Number accepted!");
}
int i = 0;
while (i <= 100) {
System.out.println(i);
if ((n1*i) <= 100) {
System.out.println(i);
}
i = i + 1;
}
System.out.println("\n*** End ***");
}
}
}
This should work. You were just finding if the number n1 was divisible by 100.

Looping this guessing game continuously

I'm fairly new to java and I was wondering how could I reset this game to ask another number after the user guessed it correctly?
Here's my code so far:
import java.util.Scanner;
public class Question2 {
public static void main(String args[]) {
Scanner keyboard = new Scanner(System.in);
int count = 0;
int a = 1 + (int) (Math.random() * 99);
int guess = 0;
System.out.println("Welcome to the Number Guessing Game");
System.out.print("Guess a number between 0 and 100 or enter -1 to end: ");
while (guess != a) {
guess = keyboard.nextInt();
count++;
if (guess < 0 || guess > 100){
if(guess == -1){
System.out.print("Thank you for playing the game!");
break;
}
System.out.print("Out of bounds. Try Again: ");
continue;
}
if (guess > a) {
System.out.print("The number is lower. Try again: ");
}
else if (guess < a) {
System.out.print("The number is higher. Try again: ");
}
else if (guess == a) {
System.out.println("Congratulations. You guessed the number in "
+ count + " tries!");
}
}
}
}
Just wrap your entire code (except for the scanner initialization) in a while loop that is always true. That way, when one game ends, it will start a new one. Then, instead of breaking your game's while loop when the user enters a -1, just use System.exit(0), which will end your program with a status code of 0, indicating that the program executed successfully.
public static void main(String[] args) throws IOException {
Scanner keyboard = new Scanner(System.in);
while (true) {
int count = 0;
int a = 1 + (int) (Math.random() * 99);
int guess = 0;
System.out.println("Welcome to the Number Guessing Game");
System.out.print("Guess a number between 0 and 100 or enter -1 to end: ");
while (guess != a) {
guess = keyboard.nextInt();
count++;
if (guess < 0 || guess > 100) {
if (guess == -1) {
System.out.print("Thank you for playing the game!");
System.exit(0);
}
System.out.print("Out of bounds. Try Again: ");
continue;
}
if (guess > a) {
System.out.print("The number is lower. Try again: ");
} else if (guess < a) {
System.out.print("The number is higher. Try again: ");
} else if (guess == a) {
System.out.println("Congratulations. You guessed the number in "
+ count + " tries!");
}
}
}
}
Wrap your code in a while (true) this will keep on running your code for ever and ever. Make sure you are also updating your random a after every game and your count. Then from there just check if guess is ever -1 and return when it is. When you call return it will end the method which ends your game.
Scanner keyboard = new Scanner(System.in);
while (true){
int count = 0;
int a = 1 + (int) (Math.random() * 99);
int guess = 0;
System.out.println("Welcome to the Number Guessing Game");
System.out.print("Guess a number between 0 and 100 or enter -1 to end: ");
while (guess != a) {
guess = keyboard.nextInt();
count++;
if (guess==-1){
System.out.print("Thank you for playing the game!");
return;
}else if (guess < 0 || guess > 100){
System.out.print("Out of bounds. Try Again: ");
continue;
}
if (guess > a) {
System.out.print("The number is lower. Try again: ");
}
else if (guess < a) {
System.out.print("The number is higher. Try again: ");
}
else if (guess == a) {
System.out.println("Congratulations. You guessed the number in "
+ count + " tries!");
}
}
}
You need to:
move your end game condition in the while condition like this while(guess != -1)
move the welcome greetings inside the loop
move the thank you greeting after the game loop is done
reset count and a when the user won a game in order to start fresh
reset guess on every iteration
Now even if the player guesses the number, the loop does not end and the game loop can be stopped only intentionally (by entering -1 = current break condition):
import java.util.Scanner;
public class Question2 {
public static void main(String args[]) {
Scanner keyboard = new Scanner(System.in);
int count = 0;
int a = 1 + (int) (Math.random() * 99);
int guess = 0;
System.out.println("Welcome to the Number Guessing Game");
while (guess != -1) {
System.out.print("Guess a number between 0 and 100 or enter -1 to end: ");
guess = keyboard.nextInt();
count++;
if (guess < 0 || guess > 100){
System.out.print("Out of bounds. Try Again: ");
continue;
}
if (guess > a) {
System.out.print("The number is lower. Try again: ");
}
else if (guess < a) {
System.out.print("The number is higher. Try again: ");
}
else if (guess == a) {
a = 1 + (int) (Math.random() * 99);
System.out.println("Congratulations. You guessed the number in " + count + " tries!");
count = 0;
}
guess = 0;
}
System.out.print("Thank you for playing the game!");
}
The code can be refactored even more, for example extract functionality into functions in order to make the code more readable. This also leads to easier maintanence should the variables change or should more conditions come. For example the code can be refactored like this:
import java.util.Scanner;
public class Question2 {
public static void main(String args[]) {
Scanner keyboard = new Scanner(System.in);
int a = 0;
int count = 0;
int guess = 0;
startNewGame();
System.out.println("Welcome to the Number Guessing Game");
while (guess != -1) {
System.out.print("Guess a number between 0 and 100 or enter -1 to end: ");
guess = keyboard.nextInt();
count++;
if (guess < 0 || guess > 100){
System.out.print("Out of bounds. Try Again: ");
continue;
}
if (guess > a) {
System.out.print("The number is lower. Try again: ");
}
else if (guess < a) {
System.out.print("The number is higher. Try again: ");
}
else if (guess == a) {
System.out.println("Congratulations. You guessed the number in " + count + " tries!");
startNewGame();
}
resetGuess();
}
System.out.print("Thank you for playing the game!");
}
private static int generateNewA() {
return 1 + (int) (Math.random() * 99);
}
private static void startNewGame() {
a = generateNewA();
count = 0;
}
private static void resetGuess() {
guess = 0;
}
}
Another solution is to use two nested loops, but IMO for this case loop in a loop is too much and makes the source unnecessary complex.

Converting a do while code to methods JAVA

I'm studying engineering at school and part of the course is to complete Computer Programming 1, which I am currently undertaking. I have been finding it very challenging seeing as I have no prior programming experience, especially this week.
The goal of this weeks quiz/assignment is to convert the code we made last week into methods and only perform 2 calls (not that I know what that means). We are learning Java and I have a textbook here that I have been getting help from up until now but I don't find the examples they display very helpful. I will paste my code below and if anyone can help me with how to convert it into methods I would hugely appreciate it!! Thanks
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String session = "C";
System.out.println("Welcome to the Assignment Manager");
System.out.println("This application will allow you to track your assignment across all your topics. It will keep track of the number of assignments, the due dates, their weighting, if they are group based and who is in your group. You will be able to log your progress with the assignment and calculate your current grade for specific topics");
System.out.println("+-+-+-+-+-+-+-+-+");
System.out.println("This program was created by <<wfeffe>>");
System.out.println("<<11th March 2014>>, for the CP1 topic in Semester 1 2014");
System.out.println("+-+-+-+-+-+-+-+-+");
System.out.println(" ");
int score;
do {
do {
System.out.println("Display menu: ");
System.out.println(" 0. Add a new topic");
System.out.println(" 1. Add a new assignment to an existing topic");
System.out.println(" 2. Record a result for an existing assignment");
System.out.println(" 3. Quit");
score = input.nextInt();
} while (score > 4 || score < 0);
do {
System.out.println("Display menu: ");
System.out.println(" 0. COMP1001");
System.out.println(" 1. COMP1002");
System.out.println(" 2. COMP1003");
System.out.println(" 3. COMP1004");
score = input.nextInt();
} while (score >= 4 || score < 0);
if (score == 0 || score == 1) {
double gradeTotal = 0;
for (int i = 1; i < 5; i++) {
do {
System.out.println("Enter score for assignment " + i + " from 0-100: ");
int grade = input.nextInt();
if (gradeTotal >= 0 && gradeTotal <= 100) {
gradeTotal += (grade * .25);
}
} while (!(gradeTotal >= 0 && gradeTotal <= 100));
}
System.out.println("Total is : " + gradeTotal);
} else {
System.out.println("Enter all ten assignments: ");
double gradeTotal = 0;
for (int i = 1; i < 11; i++) {
do {
System.out.println("Enter score for assignment " + i + " from 0-100: ");
int grade = input.nextInt();
if (gradeTotal >= 0 && gradeTotal <= 100) {
gradeTotal += (grade * .1);
}
} while (!(gradeTotal >= 0 && gradeTotal <= 100));
}
System.out.println("Total is : " + gradeTotal);
}
System.out.println("Do you wish to continue or end session? (C to continue)");
} while (input.nextLine().equalsIgnoreCase("C"));
}
}
What they mean by converting it into methods is placing code within methods, then calling those methods.
class Main {
public static void main(String[] args) {
method1();
method2();
}
private static void method1() {
}
private static void method2() {
}
}
Im not sure if youre supposed to used static. If not, you need to look into creating instances.
Right now, everything is in your main method. Im sure the goal is to move your code into 2 seperate methods (depending on how your cose processes), then call those methods from thw method method.
Chances are, you are going to need to make reference variables (for your Scanner and possibly other things), so you can access it from multiple methods. (make current local variables like scanner field variables if needed)
A call is when you direct the program to enter or execute some method:
System.out.println();
^^^^^^^^^^^ This is a call to the println() method
What your teacher seems to be asking you to do is factor your code into methods. I will try to help you factor out some of your code into methods, but I will not do any writing for you.
Factoring is a process that works somewhat like factoring a mathematical expression. In general, you can identify a piece of code for factoring out if you see repetitive sections of code that all do the same task, or very similar pieces of code that only differ in similar places. For example, you have:
int grade = input.nextInt();
if (gradeTotal >= 0 && gradeTotal <= 100) {
gradeTotal += (grade * .25);
}
I can see at least one other place where this is repeated very nearly verbatim, with only one difference. This would be a good candidate for factoring, perhaps into a method which has this code but replaces the different spot with a variable. Maybe you can even factor some code beyond the code I mentioned.
Hope this helped!
They just want you to extract the methods out and call them.
You can create a new scanner in each method or you can just declare it as a variable of your overall class and use it there.
So you would do this:
public class YourClass
{
static Scanner input;
public static void main(String[] args)
{
input = new Scanner(System.in);
do {
method1();
method2();
//...
//other code here
//...
} while (input.nextLine().equalsIgnoreCase("C"));
}
public static void method1()
{
int score;
do {
System.out.println("Display menu: ");
System.out.println(" 0. Add a new topic");
System.out.println(" 1. Add a new assignment to an existing topic");
System.out.println(" 2. Record a result for an existing assignment");
System.out.println(" 3. Quit");
score = input.nextInt();
} while (score > 4 || score < 0);
}
public static void method2()
{
int score;
do {
System.out.println("Display menu: ");
System.out.println(" 0. COMP1001");
System.out.println(" 1. COMP1002");
System.out.println(" 2. COMP1003");
System.out.println(" 3. COMP1004");
score = input.nextInt();
} while (score >= 4 || score < 0);
}
}
First off, line 22 (including spaces) needs to have >= 4 not just > 4. (Yes the cut of code was on purpose).
What you want to do is have one call that prints out all the menu stuff and returns the int "score".
private int displayMenu() {
Scanner input = new Scanner(System.in);
String session = "C";
System.out.println("Welcome to the Assignment Manager");
System.out.println("This application will allow you to track your assignment across all your topics. It will keep track of the number of assignments, the due dates, their weighting, if they are group based and who is in your group. You will be able to log your progress with the assignment and calculate your current grade for specific topics");
System.out.println("+-+-+-+-+-+-+-+-+");
System.out.println("This program was created by <<Brayden Paver>>");
System.out.println("<<11th March 2014>>, for the CP1 topic in Semester 1 2014");
System.out.println("+-+-+-+-+-+-+-+-+");
System.out.println();
int score;
do {
do {
System.out.println("Display menu: ");
System.out.println(" 0. Add a new topic");
System.out.println(" 1. Add a new assignment to an existing topic");
System.out.println(" 2. Record a result for an existing assignment");
System.out.println(" 3. Quit");
score = input.nextInt();
} while (score >= 4 || score < 0);
do {
System.out.println("Display menu: ");
System.out.println(" 0. COMP1001");
System.out.println(" 1. COMP1002");
System.out.println(" 2. COMP1003");
System.out.println(" 3. COMP1004");
score = input.nextInt();
} while (score >= 4 || score < 0);
return score;
}
And another that takes score and performs the operation.
public void performOperation(int score) {
if (score == 0 || score == 1) {
double gradeTotal = 0;
for (int i = 1; i < 5; i++) {
do {
System.out.println("Enter score for assignment " + i + " from 0-100: ");
int grade = input.nextInt();
if (gradeTotal >= 0 && gradeTotal <= 100) {
gradeTotal += (grade * .25);
}
} while (!(gradeTotal >= 0 && gradeTotal <= 100));
}
System.out.println("Total is : " + gradeTotal);
} else {
System.out.println("Enter all ten assignments: ");
double gradeTotal = 0;
for (int i = 1; i < 11; i++) {
do {
System.out.println("Enter score for assignment " + i + " from 0-100: ");
int grade = input.nextInt();
if (gradeTotal >= 0 && gradeTotal <= 100) {
gradeTotal += (grade * .1);
}
} while (!(gradeTotal >= 0 && gradeTotal <= 100));
}
System.out.println("Total is : " + gradeTotal);
}
System.out.println("Do you wish to continue or end session? (C to continue)");
}
Then in your psvm:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
do {
int score = displayMenu();
performOperation(score);
//Or performOperation(displayMenu());
} while(input.nextLine().equalsIgnoreCase("C"));
}

Elevator Simulator help in Java

I'm having trouble finishing a basic elevator simulator in Java. What I have so far is an option that lets the user input whether they want to choose a floor, to pull a fire alarm, or to quit the simulation. When they choose select floor, they can pick any floor from 1 to 100, except 13. What I can't figure out how to do is to get the simulation to track their current floor so that they can go down. This is what I have so far:
public class Elevator {
public Elevator() {}
public void selectFloor() {
Scanner scnr = new Scanner(System.in);
int newFloor;
System.out.println("Enter the floor you'd like to go to ==> ");
newFloor = scnr.nextInt();
if (newFloor > 100 || newFloor < 0 || newFloor == 13) {
System.out.println("Invalid selection");
}
else if (newFloor <= 100 && newFloor > 0 && newFloor != 13) {
for (int i = 1; i <= newFloor; i++)
System.out.println("..." + i);
System.out.println("Ding!");
}
}
public void fireAlarm() {
System.out.println("Danger, you must exit the building now!");
}
}
Also, would it be helpful to post my other class for this program?
The Elevator should have a currentFloor field, like so:
private int currentFloor;
Then, in selectFloor, you need to find the direction. Also, in selectFloor, the else if is unnecessary.
public class Elevator {
private int currentFloor;
public Elevator() {
currentFloor = 0;
}
public void selectFloor() {
Scanner scnr = new Scanner(System.in);
int newFloor;
System.out.println("Enter the floor you'd like to go to ==> ");
newFloor = scnr.nextInt();
if (newFloor > 100 || newFloor < 0 || newFloor == 13) {
System.out.println("Invalid selection");
}
else { // The if was not necessary
int direction = 0;
if(currentFloor < newFloor){
direction = 1; // going up;
} else if (currentFloor > newFloor) {
direction = -1; //going down;
} else {
direction = 0; //going nowhere;
}
for (; currentFloor != newFloor; currentFloor += newFloor)
System.out.println("..." + i);
System.out.println("Ding!");
}
}
public void fireAlarm() {
System.out.println("Danger, you must exit the building now!");
}
}
Note: I haven't tested this yet, so I can't be sure it's correct.
Give your Elevator object a class variable by adding a private int floor; directly under the class opening tag. (Above the Elevator class constructor.) This variable will be tied directly to the Elevator object that contains it.
That way when you create your Elevator by using new Elevator you'll also have an int value always available to hold the floor. To access this value, build a getter and setter method. They should look like the following:
public void setFloor(int floor) {
this.floor = floor;
}
public int getFloor() {
return floor;
}
You can then call these two methods to set the floor number and get the floor number. To keep track, in your selectFloor method you'll need to use setFloor and pass it the floor number after a valid selection is made. You could then use getFloor to determine whether it would be going up or down.
To have your constructor set the floor variable at 1 when a new Elevator object is created. Simply change your constructor to look like this:
public Elevator() {
setFloor(1);
}
Hope this helps! If you have any questions on how those things are working let me know, I'll try to provide more details.
I just inserted a new method called backToBasement() and tied it into your selectFloor() method. Hope its helpful.
public void selectFloor() {
Scanner scnr = new Scanner(System.in);
int newFloor;
System.out.println("Enter the floor you'd like to go to ==> ");
newFloor = scnr.nextInt();
if (newFloor > 100 || newFloor < 0 || newFloor == 13) {
System.out.println("Invalid selection");
}
else if (newFloor <= 100 && newFloor > 0 && newFloor != 13) {
for (int i = 1; i <= newFloor; i++)
System.out.println("..." + i);
System.out.println("Ding!");
backToBasement(newFloor);
}
}
public void fireAlarm() {
System.out.println("Danger, you must exit the building now!");
}
public void backToBasement(int newFloor){
for (int i=newFloor; i>0;i--){
System.out.println("..." + i);
}
System.out.println("Ding!... Back to Ground Level");
}

Categories