Output Problems of program - java

I would like to ask why the program prints already the answer? Even if I select on different Difficulty it is still the same.
import java.util.Scanner;
import java.util.Random;
public class GuessigGame {
public static int level(int y) {
Random ans = new Random();
int easy = 20, medium = 50, hard = 10, x;
Scanner in = new Scanner(System.in);
System.out.println("Choose Difficulty");
System.out.println("1. easy ");
System.out.println("2. medium ");
System.out.println("3. hard ");
x = in.nextInt();
switch (x) {
case 1:
System.out.println("Easy");
y = easy;
break;
case 2:
System.out.println("Medium");
y = medium;
break;
case 3:
System.out.println("Hard");
y = hard;
break;
default:
break;
}
return y;
}
public static void main(String[] args) {
int choice, difficulty = 0, answer = -1;
Scanner in = new Scanner(System.in);
Random rand = new Random();
System.out.println("\n\n1. Play Game");
System.out.println("2. Exit");
System.out.println("");
choice = in.nextInt();
int diff = 0, tries = 0, triesbot = 0, trieshu = 0;
diff = level(difficulty);
difficulty = 1 + rand.nextInt(diff);
boolean win = false;
switch (choice) {
case 1:
while (win != true) {
System.out.println(difficulty);
System.out.println("Tries: " + tries);
answer = in.nextInt();
if (answer == difficulty + 1 || answer == difficulty - 1) {
System.out.println("so close");
} else if (answer == difficulty + 2 || answer == difficulty + 2) {
System.out.println("youre answer was close");
} else if (answer == difficulty + 3 || answer == difficulty - 3) {
System.out.println("try more youre close");
} else if (answer == difficulty + 4 || answer == difficulty - 4) {
System.out.println("try youre best buddy!");
} else if (answer > difficulty + 4 || answer < difficulty - 4) {
System.out.println("so far!");
} else if (tries == 0) {
System.out.print("Game Over!");
win = true;
} else if (answer == difficulty) {
System.out.println("You got the correct answer!!!!");
win = true;
} else {
}
tries++;
}
break;
default:
System.exit(0);
break;
}
}
}
This is the output of the program:

Because you told the computer to print out the difficulty. I suggest having better names.
difficulty = 1 + rand.nextInt(diff);
boolean win = false;
switch(choice) {
case 1:
while(win != true) {
System.out.println(difficulty);
System.out.println("Tries: " + tries);

Related

I am trying to add an option to replay or end the game. Also, my results aren't popping up properly

I am trying to add an exit option to this code. Also, my results will not read correctly, and I am not sure what I am doing wrong. I've tried using a do while loop, but I can't seem to place it in the correct place.
//import Scanner Class
import java.util.Scanner;
import java.util.Random;
public class JavaMidterm {
public static void main(String[] args) {
String result = " ", symbola = " ", symbolb = " ";
Scanner s = new Scanner(System.in);
//prompt user
System.out.print("Scissor (0), rock (1), paper (2): ");
// read user choice
int choice=s.nextInt();
//Create random class object
Random random = new Random();
//Generate a random number from 0, 1, 2
int pick = random.nextInt(3);
if(choice == pick)
result = "It is a draw";
else {
if (((choice == 0) && (pick == 2)) || ((choice == 1) && (pick ==0)) || ((choice == 2) && (pick == 1)) )
result = "You won";
else
result = "You lose";
}
if(pick == 0)
symbola = "Scissor";
if(choice == 0)
symbolb = "Scissor";
//assigning symbols to the corresponding values
if(pick == 1)
symbolb = "Rock";
if(pick == 2)
symbola = "Paper";
if(choice == 2)
symbolb = "Paper";
System.out.println("The computer is" +
symbola + ". You are" + symbolb + ". " + result);
}
}
You can try my solution below. I have also included checking for invalid inputs. I also simplified the checking for your result.
//import Scanner Class
import java.util.Random;
import java.util.Scanner;
public class JavaMidterm {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
// Create random class object
Random random = new Random();
String[] choices = new String[] { "Scissor", "Rock", "Paper" };
int choice;
// prompt user
System.out.print("Scissor (0), rock (1), paper (2): ");
while (true) {
try {
String result = "";
// read user choice
choice = Integer.parseInt(s.nextLine());
if (choice < 0 || choice > 2) {
throw new Exception();
}
// Generate a random number from 0, 1, 2
int pick = random.nextInt(3);
if (choice == pick)
result = "It is a draw";
else if (((choice == 0) && (pick == 2)) || ((choice == 1) && (pick == 0))
|| ((choice == 2) && (pick == 1)))
result = "You won";
else
result = "You lose";
System.out.println("The computer is " + choices[pick] + ". You are " + choices[choice] + ". " + result);
System.out.print("Do you want to play again? Yes (0), No (1): ");
while (true) {
try {
// read user choice
choice = Integer.parseInt(s.nextLine());
if (choice < 0 || choice > 1) {
throw new Exception();
}
if (choice == 0)
System.out.print("Scissor (0), rock (1), paper (2): ");
break;
} catch (Exception e) {
System.out.println("Invalid input.");
System.out.print("Do you want to play again? Yes (0), No (1): ");
}
}
if (choice == 1) {
break;
}
} catch (Exception e) {
System.out.println("Invalid input.");
System.out.print("Scissor (0), rock (1), paper (2): ");
}
}
s.close();
}
}
I assume that you wish to end the game in case of a "win" and continue the game in case of "losing". Assuming that the code can be modified like below,
boolean isGoodToContinue = true;
while (isGoodToContinue) {
String result = " ", symbola = " ", symbolb = " ";
Scanner s = new Scanner(System.in);
// prompt user
System.out.print("Scissor (0), rock (1), paper (2): ");
// read user choice
int choice = s.nextInt();
// Create random class object
Random random = new Random();
// Generate a random number from 0, 1, 2
int pick = random.nextInt(3);
if (choice == pick)
result = "It is a draw";
else {
if (((choice == 0) && (pick == 2)) || ((choice == 1) && (pick == 0))
|| ((choice == 2) && (pick == 1))) {
result = "You won";
isGoodToContinue = false;
}
else {
result = "You lose";
isGoodToContinue = true;
}
}

making java tic tac toe vs computer [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 4 years ago.
Thats my tictactoe game and i have this problem i cant find out...When i compile my programm
Welcome To Tic Tac Toe Professor Falken!
***Use Numbers 1-9 To Select A Square***
_1_|_2_|_3_|
_4_|_5_|_6_|
_7_|_8_|_9_|
You Go First!
___|___|___|
___|___|___|
___|___|___|
Player X, enter move (1 - 9):
10
INVALID MOVE: Enter number 1 - 9 only:
5
___|___|___|
___|_X_|___|
___|___|___|
Player O, enter move (1 - 9):
___|___|___|
___|_X_|_O_|
___|___|___|
Player X, enter move (1 - 9):
4
___|___|___|
_X_|_X_|_O_|
___|___|___|
Player O, enter move (1 - 9):
And stops there, i dont know why can anyone help me?
import java.util.Random;
import java.util.Scanner;
public class TicTacToe {
private Scanner in;
private boardPiece[][] board = {{new boardPiece(),new boardPiece(),new boardPiece()},
{new boardPiece(),new boardPiece(),new boardPiece()},
{new boardPiece(),new boardPiece(),new boardPiece()}};
private char turn = 'X';
private boolean win = false;
private int count = 0;
private Random random = new Random();
private int randomNumber = random.nextInt(9);
public static void main(String [] args)
{
int replay;
TicTacToe game = new TicTacToe();
game.in = new Scanner(System.in);
System.out.println("Welcome To Tic Tac Toe Professor Falken!");
System.out.println("***Use Numbers 1-9 To Select A Square***");
System.out.println("_1_|_2_|_3_|");
System.out.println("_4_|_5_|_6_|");
System.out.println("_7_|_8_|_9_|");
System.out.println(" n You Go First!");
game.play();
System.out.println("Would you like to play again?(1 = Yes & 2 = No): ");
replay = game.in.nextInt();
while(replay != 2){
game.init();
game.play();
System.out.println("Would you like to play again?(1 = Yes & 2 = No): ");
replay = game.in.nextInt();
}
game.in.close();
System.out.println("How about a nice game of chess :p");
}
public void play()
{
printBoard();
while(!win)
move();
}
public void printBoard()
{
for(int x=0; x<3; x++){
for(int y=0; y<3; y++){
System.out.print(board[x][y].piece);
}
System.out.println();
}
}
public void move()
{
int move = 0;
String valid = "";
System.out.println("Player " + turn + ", enter move (1 - 9): ");
if(turn == 'O') {
move = randomNumber; }
else {
move = in.nextInt();
}
valid = checkMove(move);
while(valid != "ok")
{
if(turn == 'X') {
System.out.println("INVALID MOVE: "+ valid);
move = in.nextInt();
}
else {
move = randomNumber;
}
valid = checkMove(move);
}
count++;
board[(move-1)/3][(move-1)%3].piece = "_"+turn+"_|";
board[(move-1)/3][(move-1)%3].player = turn;
board[(move-1)/3][(move-1)%3].used = true;
printBoard();
if(count >= 5)
checkWin(move);
if(turn == 'X')
turn = 'O';
else
turn = 'X';
}
public String checkMove(int move)
{
if(move < 1 || move > 9)
return "Enter number 1 - 9 only: ";
else
if(board[(move-1)/3][(move-1)%3].used)
return "That move has been used. Enter another move (1 - 9): ";
else
return "ok";
}
public void checkWin(int move)
{
for(int x = 0; x<3; x++){ //Horizontal
if((board[x][0].used && board[x][1].used && board[x][2].used) &&
(board[x][0].player == board[x][1].player && board[x][0].player == board[x][2].player)){
System.out.println("Congratulations Player " + turn + "!!! You win!");
win = true;
return;
}
}
for(int y = 0; y<3; y++)
{
if((board[0][y].used && board[1][y].used && board[2][y].used) &&
(board[0][y].player == board[1][y].player && board[0][y].player == board[2][y].player)){
System.out.println("Congratulations Player " + turn + "!!! You win!");
win = true;
return;
}
}
if((board[0][0].used && board[1][1].used && board[2][2].used) &&
(board[0][0].player == board[1][1].player && board[0][0].player == board[2][2].player)){
System.out.println("Congratulations Player " + turn + "!!! You win!");
win = true;
return;
}
if((board[2][0].used && board[1][1].used && board[0][2].used) &&
(board[2][0].player == board[1][1].player && board[2][0].player == board[0][2].player))
{
System.out.println("Congratulations Player " + turn + "!!! You win!");
win = true;
return;
}
if(count==9){
System.out.println("Draw! Nobody Wins (ยด???`)");
win = true;
return;
}
}
public void init()
{
for(int x=0;x<3;x++){
for(int y=0;y<3;y++){
board[x][y] = new boardPiece();
}
}
turn = 'X';
win = false;
count = 0;
}
class boardPiece{
public String piece;
public char player;
public boolean used;
boardPiece(){
piece = "___|";
used = false;
}
}
}
I made a some changes in move and checkMove
public void move() {
int move = 0;
Boolean valid = false;
System.out.println("Player " + turn + ", enter move (1 - 9): ");
if (turn == 'O') {
move = randomNumber;
} else {
move = in.nextInt();
}
valid = checkMove(move);
while (!valid) {
if (turn == 'X') {
move = in.nextInt();
} else {
move = random.nextInt(9);
}
valid = checkMove(move);
}
count++;
board[(move - 1) / 3][(move - 1) % 3].piece = "_" + turn + "_|";
board[(move - 1) / 3][(move - 1) % 3].player = turn;
board[(move - 1) / 3][(move - 1) % 3].used = true;
printBoard();
if (count >= 5) {
checkWin(move);
}
if (turn == 'X') {
turn = 'O';
}else {
turn = 'X';
}
}
public Boolean checkMove(int move) {
if (move < 1 || move > 9) {
System.out.println("INVALID MOVE: Enter number 1 - 9 only: ");
return false;
}else if (board[(move - 1) / 3][(move - 1) % 3].used) {
System.out.println("INVALID MOVE: That move has been used. Enter another move (1 - 9): ");
return false;
}else {
return true;
}
}

Validate a course code using a method in java

I have to get my course code to validate. The course code is set to a number 1-7 and the choice has to be within this range. Each course is worth 3 credits. The user can not register for more than 9 credits. The user can not register for the same course more than once. I am having trouble with the repeat course code.
Here is my code:
package u6a1_consoleregisterforcourse;
import java.util.Scanner;
public class U6A1_ConsoleRegisterForCourse {
public static void main(String[] args) {
System.out.println("Quenten's Copy");
Scanner input = new Scanner(System.in);
//choice is the current menu selection
//firstChoice is the first menu selection mande by the user
//secondChoice is the second menu selection mande by the user
//thirdChoice is the third menu selection mande by the user
// a choice of 0 means the choice has not been made yet
int choice;
int firstChoice = 0, secondChoice = 0, thirdChoice = 0;
int totalCredit = 0;
String yesOrNo = "";
do {
choice = getChoice(input);
switch (ValidateChoice(choice, firstChoice, secondChoice, thirdChoice, totalCredit)) {
case -1:
System.out.println("**Invalid** - Your selection of " + choice + " is not a recognized course.");
break;
case -2:
System.out.println("**Invalid** - You have already registerd for this " + ChoiceToCourse(choice) + " course.");
break;
case -3:
System.out.println("**Invalid** - You can not register for more than 9 credit hours.");
break;
case 0:
System.out.println("Registration Confirmed for course " + ChoiceToCourse(choice) );
totalCredit += 3;
if (firstChoice == 0)
firstChoice = choice;
else if (secondChoice == 0)
secondChoice = choice;
else if (thirdChoice == 0)
thirdChoice = choice;
break;
}
WriteCurrentRegistration(firstChoice, secondChoice, thirdChoice);
System.out.print("\nDo you want to try again? (Y|N)? : ");
yesOrNo = input.next().toUpperCase();
} while (yesOrNo.equals("Y"));
System.out.println("Thank you for registering with us");
}
public static int getChoice(Scanner input) {
System.out.println("Please type the number inside the [] to register for a course");
System.out.println("[1]IT4782\n[2]IT4784\n[3]IT4786\n[4]IT4789\n[5]IT2230\n[6]IT3345\n[7]IT3349");
System.out.print("Enter your choice : ");
return (input.nextInt());
}
//This method validates the user menu selection
//against the given registration business rules
//it returns the following code based on the validation result
// -1 = invalid, unrecognized menu selection
// -2 = invalid, alredy registered for the course
// -3 = invalid, No more than 9 credit hours allowed
// 0 = menu selection is valid
public static int ValidateChoice(int choice, int firstChoice, int secondChoice, int thirdChoice, int totalCredit) {
// TO DO - Add Code to:
// Validate user menu selection (the int choice method argument)
// against the given registration business rules
int ValidateChoice;
if ((choice < 1) || (choice >= 8)){
ValidateChoice = -1;}
else if (secondChoice == firstChoice){
ValidateChoice = -2;}
else
{ValidateChoice = 0;}
return ValidateChoice;
}
public static void WriteCurrentRegistration(int firstChoice, int secondChoice, int thirdChoice) {
if (firstChoice == 0)
System.out.println("Current course registration: { none } " );
else if (secondChoice == 0)
System.out.println("Current course registration: { " + ChoiceToCourse(firstChoice) + " }" );
else if (thirdChoice == 0)
System.out.println("Current course registration: { " + ChoiceToCourse(firstChoice) +
", " + ChoiceToCourse(secondChoice) + " }");
else
System.out.println("Current course registration: { " + ChoiceToCourse(firstChoice) +
", " + ChoiceToCourse(secondChoice) + ", " + ChoiceToCourse(thirdChoice) + " }");
}
public static String ChoiceToCourse(int choice) {
String course = "";
switch (choice)
{
case 1:
course = "IT4782";
break;
case 2:
course = "IT4784";
break;
case 3:
course = "IT4786";
break;
case 4:
course = "IT4789";
break;
case 5:
course = "IT2230";
break;
case 6:
course = "IT3345";
break;
case 7:
course = "IT3349";
break;
default:
break;
}
return course;
}
}
The ValidateChoice method is what I am working on. This is for an academic assignment.
It is better to get rid of those firstChoice, secondChoice, thirdChoice variables and use a homogeneous collection instead:
package u6a1_consoleregisterforcourse;
import java.util.*;
public class U6A1_ConsoleRegisterForCourse {
public static final int CREDITS_PER_COURSE = 3;
public static final int MAX_CREDITS = 9;
public static final int MAX_COURSES = MAX_CREDITS / CREDITS_PER_COURSE;
private final List<Integer> registeredCourses = new ArrayList<>(MAX_COURSES);
private int totalCredit;
public static void main(String[] args) {
System.out.println("Quenten's Copy");
U6A1_ConsoleRegisterForCourse registrar = new U6A1_ConsoleRegisterForCourse();
Scanner input = new Scanner(System.in);
//choice is the current menu selection
int choice;
String yesOrNo;
do {
choice = getChoice(input);
switch (registrar.validateChoice(choice)) {
case -1:
System.out.println("**Invalid** - Your selection of " + choice + " is not a recognized course.");
break;
case -2:
System.out.println("**Invalid** - You have already registered for this " + choiceToCourse(choice) + " course.");
break;
case -3:
System.out.println("**Invalid** - You can not register for more than " + MAX_CREDITS + " credit hours.");
break;
case 0:
System.out.println("Registration Confirmed for course " + choiceToCourse(choice));
registrar.totalCredit += CREDITS_PER_COURSE;
registrar.registeredCourses.add(choice);
break;
}
registrar.writeCurrentRegistration();
System.out.print("\nDo you want to try again? (Y|N)? : ");
yesOrNo = input.next().toUpperCase();
} while (yesOrNo.equals("Y"));
System.out.println("Thank you for registering with us");
}
private static final String[] courses = {"IT4782", "IT4784", "IT4786", "IT4789", "IT2230", "IT3345", "IT3349"};
public static String choiceToCourse(int choice) {
return courses[choice - 1];
}
public static int getChoice(Scanner input) {
System.out.println("Please type the number inside the [] to register for a course");
for (int i = 1; i <= courses.length; i++)
System.out.format("[%d]%s%n", i, choiceToCourse(i));
System.out.print("Enter your choice : ");
return (input.nextInt());
}
// This method validates the user menu selection
// against the given registration business rules
// it returns the following code based on the validation result
// -1 = invalid, unrecognized menu selection
// -2 = invalid, alredy registered for the course
// -3 = invalid, No more than 9 credit hours allowed
// 0 = menu selection is valid
public int validateChoice(int choice) {
if ((choice < 1) || (choice > courses.length))
return -1;
if (registeredCourses.contains(choice))
return -2;
if (totalCredit + CREDITS_PER_COURSE > MAX_CREDITS)
return -3;
return 0;
}
public void writeCurrentRegistration() {
StringBuilder sb = new StringBuilder("Current course registration: ");
if (registeredCourses.isEmpty())
sb.append(" { none }");
else {
sb.append("{ ");
boolean first = true;
for (int i : registeredCourses) {
if (first)
first = false;
else
sb.append(", ");
sb.append(choiceToCourse(i));
}
sb.append(" }");
}
System.out.println(sb);
}
}
You need to write 3 different validations in your code:
public static int ValidateChoice(int choice, int firstChoice, int secondChoice, int thirdChoice, int totalCredit) {
//Validation: Choice is in range of 1 and 7
if(choice > 7 || choice < 1){
return -1;
}
// Validation : No 2 course choices have same value
boolean isInvalid = firstChoice!=0 ?
(firstChoice == secondChoice ||firstChoice == thirdChoice):
(secondChoice!=0 && secondChoice==thirdChoice);
if(isInvalid) {
return -2;
}
// Validation : Total credits are not more than 9
else if(totalCredit > 9){
return -3;
}
else{
return 0;
}
}
One of your fellow course mate have also asked this question here,
Validating inputs in a function in java to avoid duplicate data other than non entry with default of 0 (No database )
Be careful of Plagiarism
With the parameters I was given, and only allowed to change the ValidateChoice method, I was able to take John McClane's answer and convert it to make it work. I thank you for the help. What I have done is simple and now makes sense.
Here it is:
public static int ValidateChoice(int choice, int firstChoice, int secondChoice, int thirdChoice, int totalCredit) {
// TO DO - Add Code to:
// Validate user menu selection (the int choice method argument)
// against the given registration business rules
if ((choice < 1) || (choice >7))
return -1;
if ((choice == secondChoice) || (choice == firstChoice))
return -2;
if (totalCredit >= 9)
return -3;
return 0;
}

Java HiLo program stops

Right now im making a HiLo game in java and i have a few problems, not sure tho if im doing it right since im very new into java.
I having problem with getting the two ints "answer" and "guess" to the 3rd method.
and i must use 3 methods in this task.
Method 1: asking for what lvl the user wants.
Method 2: The program picks a random number between max and lets the user guess.
Method 3: Will see if the guess is == to answer and if not, it lets the user to try again. and at the same time i have to save all the tries from the user.
import java.util.Scanner;
import java.util.Random;
public class oneagain {
public static void main(String[] args) {
System.out.println("Welcome HiLo!");
System.out.println("What lvl?");
System.out.println("1. Easy (1-10)");
System.out.println("2. Medium (1-100)");
System.out.println("3. Hard (1-1000)");
Scanner sc = new Scanner(System.in);
int choice = sc.nextInt();
int tries = (playGame(choice));
}
public static int playGame(int choice) {
Scanner sc = new Scanner(System.in);
int tries = 0;
if (choice == 1) {
System.out.println("Guess a number between 1 and 10");
int answer = (int) (Math.random() * 11) + 1;
int guess = sc.nextInt();
}
if (choice == 2) {
System.out.println("Guess a number between 1 and 100");
int answer = (int) (Math.random() * 101) + 1;
int guess = sc.nextInt();
}
if (choice == 3) {
System.out.println("Guess a number between 1 and 1000");
int answer = (int) (Math.random() * 1001) + 1;
int guess = sc.nextInt();
}
return tries;
}
public static void giveResponse(int answer, int guess) {
if (choice == 1) {
int tries = 0;
Scanner sc = new Scanner(System.in);
boolean y = false;
while (y == false) {
guess = sc.nextInt();
tries++;
if (guess == answer) {
y = true;
} else if (guess < answer) {
System.out.println("Guess was too low!");
System.out.println("Guess a number between 1 and 10:");
} else if (guess > answer) {
System.out.println("Guess was too high!");
System.out.println("Guess a number between 1 and 10:");
} else if (guess == answer) {
System.out.println("Score!");
System.out.println("You succeeded in " + tries + " attempt");
}
if (choice == 2) {
while (y == false) {
guess = sc.nextInt();
tries++;
if (guess == answer) {
y = true;
} else if (guess < answer) {
System.out.println("Guess was too low!");
System.out.println("Guess a number between 1 and 100:");
} else if (guess > answer) {
System.out.println("Guess was too high!");
System.out.println("Guess a number between 1 and 100:");
} else if (guess == answer) {
System.out.println("Score!");
System.out.println("You succeeded in " + tries + " attempt");
}
if (choice == 3) {
while (y == false) {
guess = sc.nextInt();
tries++;
if (guess == answer) {
y = true;
} else if (guess < answer) {
System.out.println("Guess was too low!");
System.out.println("Guess a number between 1 and 100:");
} else if (guess > answer) {
System.out.println("Guess was too high!");
System.out.println("Guess a number between 1 and 100:");
} else if (guess == answer) {
System.out.println("Score!");
System.out.println("You succeeded in " + tries + " attempt");
}
}
}
}
}
}
}
}
}

How to validate the selection menu using a loop

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

Categories

Resources