Converting a do while code to methods JAVA - 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"));
}

Related

I want to write a program that allows the user to guess a number between 0 and 100 in 7 attempts. I don't know why is this not working

public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int rnd = (int)(Math.random() * 101);
System.out.println("The program is going to give a number that is between 0 and 100 (including them). You can guess it by pressing Run.");
System.out.println("Enter your number:");
int num = scan.nextInt();
for (int count = 1; count <= 7; count++) {
while (num != rnd) {
if (num < rnd) {
System.out.println("Your guess is too low.");
}
if (num > rnd) {
System.out.println("Your guess is too high.");
}
if ((Math.abs(rnd - num) == 1) || (Math.abs(rnd - num) == 2)) {
System.out.println("But your guess is VERY close.");
}
num = scan.nextInt();
}
System.out.println("You got it right!");
}
System.out.println("You should guess it in 7 tries.");
}
}
So I used two loops and just nested them. Is that how it works for this? Right now the code is like starting with for loop and if that is true it goes to the while loop part where the guessing number takes place. Can this be fixed with just moving some codes and fixing minor areas around?
What you should do in a situation like this is do the code manually. Literally. Grab a piece of paper and pretend you're a computer. It's a good exercise, and it will help you figure out your problem.
The problem is your inner loop. It loops until they guess correctly regardless of the number of attempts. Then you force them to do it 6 more times with the outer loop.
You really only need 1 loop. I would have a single loop like this:
int attempts = 0;
int num = 0;
do {
num = scan.nextInt();
... most of the if code from your inner loop but not another scan.nextInt
} while (++attempts < 7 && num != rnd);
// and here you look at num == rnd to see if success or failures
I think you should rebuild you code to make it more clear.
Split the title (with description of the task)
Split main loop where you read user input and check it with expected number
Split output of the final result, where you print the result.
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
final int rnd = new Random().nextInt(101);
final int maxAttempts = 7;
System.out.println("The program is going to give a number that is between 0 and 100 (including them).");
System.out.println("You can guess it within maximum " + maxAttempts + " attempts by pressing Run.");
boolean success = false;
for (int attempt = 1; attempt <= maxAttempts && !success; attempt++) {
System.out.format("(%s of %s) Enter your number: ", attempt, maxAttempts);
int num = scan.nextInt();
if (num == rnd)
success = true;
else {
System.out.print("Your guess is too " + (num > rnd ? "high" : "low") + '.');
System.out.println(Math.abs(rnd - num) <= 2 ? " But it's VERY close." : "");
}
}
System.out.println(success ? "You got it right!" : "Bad luck this time. Buy.");
}
import java.util.Scanner;
class Main {
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
int rnd = (int) (Math.random() * 101);
System.out.println("The program is going to give a number that is between 0 and 100 (including them). You can guess it by pressing Run.");
System.out.println("Enter your number:");
int num = scan.nextInt();
for(int count = 1; count <= 7; count++)
{
if (num < rnd)
{
System.out.println("Your guess is too low.");
}
else if (num > rnd)
{
System.out.println("Your guess is too high.");
}
else if ((Math.abs(rnd - num) == 1) || (Math.abs(rnd - num) == 2))
{
System.out.println("But your guess is VERY close.");
}
else
System.out.println("You got it right!");
System.out.println("Enter Next number: ");
num = scan.nextInt();
}
}
}
It should work Fine.Basically Your reasoning wass wrong because You are putting a while loop inside a for loop. What you want to do is you want only 7 iteration.In those 7 iterations you are checking the conditions based on user Input.

Why do I get an error when I use cascading ifs in Java?

I have a program that takes one's income and multiplies it by a factor according to the income given. It also gives a code either 1 or 0 that defines the range of the incomes accordingly.
It seems correct on a first sight but I seem to get errors that concern the if statements that exist in the method that I use in order to calculate the incomes.
The code is the following:
import java.util.Scanner;
public class IncomeCalc{
public void Cal(double inc, int code)
{
if( code == 0 )
{
if((inc >= 0) && (inc <= 5,000))
{
System.out.println("Your tax declaration is "+ inc*0.1);
}else if((inc >= 5,001) && (inc <= 10,000))
{
System.out.println("Your tax declaration is "+ inc*0.15);
}else if((inc >= 10,001) && (inc <= 20,000))
{
System.out.println("Your tax declaration is "+ inc*0.25);
}else if(inc >= 20,001)
{
System.out.println("Your tax declaration is "+ inc*0.35);
}
}
else if( code == 1 )
{
if((inc >= 0) && (inc <= 10,000))
{
System.out.println("Your tax declaration is "+ inc*0.1);
}else if((inc >= 10,001) && (inc <= 20,000))
{
System.out.println("Your tax declaration is "+ inc*0.15);
}else if((inc >= 20,001) && (inc <= 30,000))
{
System.out.println("Your tax declaration is "+ inc*0.25);
}else if(inc >= 30,001)
{
System.out.println("Your tax declaration is "+ inc*0.35);
}
}
}
public static void main(String[] args)
{
Scanner obj = new Scanner(System.in);
System.out.println("Enter your annual income");
double income = obj.nextDouble();
Scanner obj2 = new Scanner(System.in);
System.out.println("If you are an individual choose 0 else choose 1 ");
int decl = obj2.nextInt();
Cal(income, decl);
}
}
Thank you!!!
Are you actually using commas to separate digits? if so this is your issue, also don't create 2 scanner objects, use the same one for both operations.

Using method to find an integer repeatedly

Hello my purpose is this:
Write a method that can accept values only between 10 and 50.Sample execution:Enter a number between 10 and 50Enter a number: 5Enter a number between 10 and 50Enter a number: 12Number Entered: 12.Enter a number: 0Good ByeSo as you can see it only finishes when user enters 0.And it says different things when number is between 10 and 50 or not.I deleted again my code and started but i got stuck on some points and i gave up.My final code was:
import java.util.Scanner;
public class A{
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter case number: ");
int caseVal = scan.nextInt();
switch(caseVal){
case 1:
System.out.println("Enter a number between 10 and 50");
System.out.println("Enter a number: ");
int num = scan.nextInt();
betweenMethod(num);
if(num == 0){
System.out.println("Good Bye");
break;
}
while(num != 0){
betweenMethod(num);
}
break;
case 2:
System.out.println("Enter a number to display its divisors: ");
int x = scan.nextInt();
System.out.println("The divisors of " + x + " are:");
divisorsMethod(x);
break;
}
scan.close();
}
public static void divisorsMethod(int a){
if(a <= 0)
System.out.println("The number should be greater than 0");
else{
for(int b = 1; b <= a; b++){
if(a % b == 0 && b != a)
System.out.print(b + ", ");
else if(b == a)
System.out.println(b);
}
}
}
public static void betweenMethod(int a){
Scanner inputscan = new Scanner(System.in);
if(a >= 10 && a <= 50){
System.out.println("Enter a number:");
a = inputscan.nextInt();
}
else if((a < 10 || a > 50) && a != 0){
System.out.println("Enter a number between 10 and 50");
System.out.println("Enter a number:");
a = inputscan.nextInt();
}
else{
System.out.println("Good Bye");
}
inputscan.close();
}
}
Sorry for uncut version.It is case 1.Every time i tried it didnt work fully.If anyone can help i would appreciate it.I'm sorry if i didnt write this question in rules.(Sorry for the grammar as well)THIS IS WHERE I AM STUCK= When i type 0 it doesnt say GoodBye and end the loop.Thats where i need help.TO EVERYONE THAT NEEDS ANSWER TOO:I figured out what to do.Basically we say while its not equal to zero right?I wrote a new method that (after last inputscan for variable)checks if the number is zero and prints good bye.So with this way it prints good bye and it goes to starting.But it cannot do anythink else because we said while not equal to 0.Anyway thats one solution.
Don't close() System.in
When you call inputscan.close() that closes the underlying InputStream, which is System.in.
Return the Value
Your method should be prompting for input between two values and returning a single value. Also, you could move your Scanner to a static (or class) field. Something like
private static Scanner inputscan = new Scanner(System.in);
public static int betweenMethod(final int a, final int b) {
int min = Math.min(a, b);
int max = Math.max(a, b);
while (true) {
System.out.printf("Please enter a number between %d and %d%n", min, max);
int in = inputscan.nextInt();
if ((in == 0) || (in >= min && in <= max)) {
return in;
}
}
}
Primitives1 are Passed-By Value
You need to assign the result of the call back to your value when you loop. Something like,
int num = betweenMethod(10, 50);
while (num != 0) {
System.out.printf("Number Entered: %d.%n", num);
num = betweenMethod(num);
}
System.out.println("Good Bye");
break;
1and Everything Else in Java.

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.

Adding two loops to an elevator system?

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

Categories