Using try, catch and a label for the first time [closed] - java

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
We just covered the try-catch topic in last night's lecture. It's not required to put it in this assignment, but I thought I would give it a shot.
I've been struggling with this for a while. Using a continue statement kicked it back to the start of the catch block so that the println inside it executed in a never ending loop.
So apparently there are these things called labels. I found that when I was trying to figure out how to solve the continue problem. I tried putting in a label just as I saw being done in the example code, and now it just gives me a compiler error on the break statement that says "the process flag is missing".
What am I doing wrong?
do {
// Prompt
try {
process: nbPlayers = keyboard.nextInt();
}
catch(Exception e) {
nbPlayers=0;
if (attempts<4) {
System.out.println("Incorrect input type. You have now made " + attempts +". Please enter an integer from 2 to 4.");
++attempts;
break process;
}
else {
System.out.println("Invalid input. You have now made " + attempts +". This game only allows 4 chances to input the requested number of players.\n Shutting down the program now.");
System.exit(0);
}
}
if(attempts < 4 && nbPlayers >= 2 && nbPlayers <= 4) {
valid = true;
} else if(attempts < 3) {
System.out.println("Invalid input. You have now made " + attempts +". This game only allows 4 chances to input the requested number of players.\nYou are allowed to try again.");
} else if(attempts == 3) {
System.out.println("Invalid input. You have now made " + attempts +". This game only allows 4 chances to input the requested number of players.\nYou are allowed to one more time.");
} else if(attempts == 4) {
System.out.println("Invalid input. You have now made " + attempts +". This game only allows 4 chances to input the requested number of players.\n Shutting down the program now.");
System.exit(0);
}
++attempts;
} while(!valid);

Your problem is not quite clear. Let's talk on a code.
What do you think of this ?
int attempts = 0; // is it a good initialization ?
int nbPlayers = 0; // is it a good initialization ?
boolean valid = false; // is it a good initialization ?
String nbPlayersString = "";
do {
// Prompt
try {
nbPlayersString = keyboard.nextLine();
nbPlayers = Integer.parseInt(nbPlayersString);
if(2<= nbPlayers && nbPlayers <= 4) {
valid = true;
}
else {
System.out.println("Bad Attempt " + (attempts + 1) +". Invalid number of players.");
}
}
catch(Exception e) {
nbPlayers=0;
System.out.println("Bad Attempt " + (attempts + 1) +". Wrong input type. ");
}
++attempts;
} while(!valid && attempts < 4);
if(valid)
System.out.println("GOOD JOB!");
else {
System.out.println("You have exhausted all your chances. Program will terminate!");
System.exit(0);
}
Final EDIT
It looks like you also had a cache problem with Scanner.nextInt() after entering an invalid value (string instead of integer). So, in the attempts following, the Scanner cache still had the bad value and considered it.

Related

Basic Java HiLow guessing game

I am fully aware this question has been asked many times, it is a classic first year problem in CSC. I am not looking for the solution to the problem itself. I think I have it basically done however I am missing something that I cannot find how to do.
Here is my code:
import java.util.Scanner;
import java.util.Random;
public class HiLow
{
public static void main (String[] args)
{
Random generator = new Random();
Scanner scan = new Scanner(System.in);
int num1,guess;
int count = 0;
num1 = generator.nextInt(100) + 1;
while(true) {
System.out.print("Enter an integer between 1 or 100 or enter 0 at anytime to quit: ");
guess = scan.nextInt();
count++;
if(guess == num1 || guess == 0) {
if(guess == 0) {
System.out.println("Thanks for playing");
break;
}
System.out.println("Congrats you've guessed correct and your total guesses is " + count );
break;
}
else if (guess > 100 || guess < 1) {
System.out.print("I see you cannot follow instructions. I said ");
count--;
}
else if (guess > num1) {
System.out.println("You have guessed too high. ");
}
else {
System.out.println("You have guessed too low.");
}
}
}
}
My problem is i am required to prompt the user at the point of "if the user quits or successfully guesses the correct number, prompt the user to see if they wish to play again". I am lost and not sure how to continue my while loop from the beginning after my breaks. Is there a way to end the break condition i have from (guess == num1 || guess ==0) and direct my program to start again at the while(true) statement?
Thanks
I will say search up continue;
Tips to help further:
The continue statement is used to bring the loop back to the start, try it instead of a break where you want the user to continue.
You need some sort of check if the user wants to continue, (try asking them to type in some specific int you check, p.s negative numbers are integers as well)
#Ahmed thinks you should continue, I would rather not break, or conditionally break.
Well there are multiple ways you could accomplish this, One would be to just to prompt the user with a "press q to quit" dialogue using the Scanner class where .next() returns the String when the user hits enter:
if(guess == num1 || guess == 0) {
if(guess == 0) {
System.out.println("Thanks for playing");
}else{
System.out.println("Congrats you've guessed correct and your total guesses is " + count );
}
System.out.println("would you like to play again [y/n]?");
if(scan.next().equals("y")){
num1 = generator.nextInt(100) + 1;
count=0;
}else{
break;
}
}
If thats what you mean. Hopefully I helped.
or maybe you can have it only quit at zero, if so just remove that second break and replace it with num1 = generator.nextInt(100) + 1; to set the new value to guess.

Hangman while loop not working with ||

I have the following while-loop for a game of Hangman I'm working on:
while(amountOfGuessesLeft > 0 || !wordComplete){
System.out.println("The word now looks like this: " + filteredWord);
System.out.println("You have " + amountOfGuessesLeft + " guesses left");
System.out.print("Your guess: ");
try {
guess = br.readLine();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(guess.length() == 0 || guess.length() > 1){
System.out.println("Please just type one letter. Try again.");
}else if(wordSelected.contains(guess) || wordSelected.contains(guess.toUpperCase())){
System.out.println("That guess is correct.");
filteredWord = showGuess(filteredWord, wordLetters, guess.toUpperCase().charAt(0));
if(!filteredWord.contains("_")){
wordComplete = true;
}
}else{
System.out.println("There are no " + guess.toUpperCase() + "'s in this word.");
amountOfGuessesLeft--;
}
}
When the while-loop condition is just amountOfGuessesLeft > 0, everything works fine. However, when I add || !wordComplete, neither condition is applied and the loop never ends. It doesn't throw any errors either. Any help would be appreciated.
You need to use &&.
You want to run the loop as long as there are any guesses left and the user hasn't found the word yet.
Currently, if you run out of guesses and still haven't found the word, !wordComplete will evaluate to true and allows the loop to be executed again.

How to get method to recognize else part of if statement? [duplicate]

This question already has answers here:
How can I check for invalid input and loop until the input is valid?
(3 answers)
Closed 5 years ago.
I've made a street craps game and have an error checker in the beginning to make sure the input is valid, I put it in an if statement and then have the rest of the code (for valid inputs) as the else but it isn't recognizing the else part when the user puts in a valid number.
public void play() { //method
System.out.println("Please pick a number.");
guess = scan.nextInt();
if (guess == 7 || guess == 1 || guess == 0 || guess > 12) {
System.out.println("Sorry, that is an invalid input, please choose another number.");
guess = scan.nextInt();
} else {
int roll = dieOne.roll();
int roll2 = dieTwo.roll();
int rollSums = roll + roll2;
System.out.println(roll + "+" + roll2);
while (rollSums != 7) {
if (guess == rollSums) {
System.out.println("Congratulations, you win! Your number was rolled before a seven was rolled!");
rollSums = 7;
guess = 7;
} else {
roll = dieOne.roll();
roll2 = dieTwo.roll();
rollSums = roll + roll2;
System.out.println(roll + "+" + roll2);
}
}
if (rollSums != guess) {
System.out.println("Sorry, your number was not rolled before a seven was rolled.");
}
}
}
I guess you want to execute the if part until the if condition is not satisfied, and then you want to execute the else part. If this is what you want you need to execute the if part as a while loop, and the else part as code after the while loop.
You need a while loop to make sure you get a good input first, and then do the game logic, like this:
int guess = scan.nextInt();
while (guess == 7 || guess == 1 || guess == 0 || guess > 12){
System.out.println("Sorry, that is an invalid input, please choose another number.");
guess = scan.nextInt();
}
//Game Logic (Stuff in else section)

Reading input using Scanner causes an infinite loop in Java [duplicate]

This question already has answers here:
How to handle infinite loop caused by invalid input (InputMismatchException) using Scanner
(5 answers)
Closed 5 years ago.
In my program I'm trying to get a user to input an int between 1-3 and then do something based off what they type. If it is not a number or not one of the options then it will allow them to reenter a valid option.
The issue I have is I'm having trouble brainstorming how to not have it infinitely loop and just allow them to enter in a number after the console tells them they entered an invalid input.
int i = 0;
while (i < 1) {
try {
int level = scan.nextInt();
i+=1;
if (level == 1) {
System.out.println("You selected level 1!");
//Start the game
} else if (level == 2) {
System.out.println("You selected level 2!");
//Start the game
} else if (level == 3) {
System.out.println("You selected level 3!");
//Start the game
} else {
System.out.println("That's not an option!");
i-=1;
}
} catch(InputMismatchException input) {
System.out.println("That's not an option!");
i-=1;
}
}
When you input an invalid input, you need to clear it. Add scan.next() when input exception triggered so as to clear it with next():
catch(InputMismatchException input) {
System.out.println("That's not an option!");
scan.next();
i-=1;
}
Not quite the answer you were expecting, but: refactor this code. Remember the basics of java, where every functional bit has its own method. So use a method that reads the input, and returns the level selected (or -1 if nothing):
int readInput() {
// your code here, returning either the level or -1 on bad input
}
And then call that for your read loop:
int selected;
do {
selected = readInput();
} while(selected < 1);
You are better off writing the code like this:
while(true){
try{
int level = scan.nextInt();
if(level==1){
System.out.println("You selected level 1!");
break;
}else if(level==2){
System.out.println("You selected level 2!");
break;
}else if(level==3){
System.out.println("You selected level 3!");
break;
}else{
System.out.println("That's not an option!");
continue;
}
}catch(InputMismatchException input){
System.out.println("That's not an option!");
continue;
}
}
continue will immediately resume execution of the loop at the top, and break will immediately jump too the closing brace } of the while. This removes the use of the i counter variable, which was entirely useless to the code. Also, this code will never run indefinitely, unless the user indefinitely enters improper values!
Hope this helped, good luck!
You can proceed in a much simpler way. The 3 valid cases are very similar and can be treated as one, the game can be started only once after the loop because we know that once the loop exits, level has a valid value.
boolean valid = false;
int level;
do {
try {
level = scan.nextInt();
valid = 1 <= level && level <= 3;
if (valid) {
System.out.println(String.format("You selected level %d !",level));
} else {
System.out.println("That's not an option!");
}
} catch(InputMismatchException input) {
scan.next();
System.out.println("That's not an option!");
}
} while (!valid);
// start the game

Java do while loops not looping

As far as I have read so far in my textbook for the class, in the modules for my class and in 2+ hours of searching, I cannot figure out why my code is not working.
The do while loop in the main method is working properly but the do while loops in my get methods are not looping. I put in the wrong number, I get the error message and then instead of asking for the number again, it moves on to the next get method.
I hope it is something simple that I have overlooked but I would appreciate any help I could get on this.
Here is the code for my getHome method:
public static int getHome()
{
int homeNum;
String home;
do
{
home = JOptionPane.showInputDialog(null,"Enter 1(apartment), 2(house),"
+ " or 3(dorm).","Dwelling Type", JOptionPane.QUESTION_MESSAGE);
homeNum = Integer.parseInt(home);
if(!(homeNum == 1) && !(homeNum == 2) && !(homeNum == 3))
{
JOptionPane.showMessageDialog(null, "The value for dwelling type "
+ "must be 1(apartment), 2(house), or 3(dorm)", "Dwelling"
+ "Type Error", JOptionPane.ERROR_MESSAGE);
}
return homeNum;
}
while(homeNum < 0 || homeNum > 3);
And the code in the main method that calls this method:
public static void main(String[] args)
{
String response;
do
{
petRec(getHome(), getHours());
response = JOptionPane.showInputDialog(null, "Do you want to continue?" +
"\nEnter Y for yes and anything else for no.", "Continue?", +
JOptionPane.QUESTION_MESSAGE);
}
while(response.equalsIgnoreCase("y"));
}
Just for clarification here is the petRec method:
public static void petRec(int homeType, double hoursAtHome)
{
String pet;
if(homeType == 1 && hoursAtHome >= 10)
pet = "Cat";
else
if(homeType == 1 && hoursAtHome < 10)
pet = "Hamster";
else
if(homeType == 2 && hoursAtHome >= 18)
pet = "Pot-Bellied Pig";
else
if(homeType == 2 && hoursAtHome >= 10 && hoursAtHome <= 17)
pet = "Dog";
else
if(homeType == 2 && hoursAtHome < 10)
pet = "Snake";
else
if(homeType == 3 && hoursAtHome > 6)
pet = "Fish";
else
if(homeType == 3 && hoursAtHome < 6)
pet = "Ant Farm";
else
pet = "Nothing";
JOptionPane.showMessageDialog(null, "You should get a " + pet + "!",
"Recommended Pet", JOptionPane.INFORMATION_MESSAGE);
}
Last year I took intro to Visual Basic and had infinite loops, this year I'm taking Java and can't get the loop to repeat.
The getHours method is structured almost identical to the getHome method just with different variables and wording in the prompt.
The program is supposed to display the error message when a number that is not 1, 2 or 3 is entered and then loop to ask you for the number again. It displays the error message but then goes on to ask for the hours.
Again I very much appreciate any help that can be offered. This assignment isn't due until Saturday but I only have 2 days off to work on this.
Thank you in advance for your help :)
Move the return statement to outside the loop:
public static int getHome()
{
int homeNum;
String home;
do
{
home = JOptionPane.showInputDialog(null,"Enter 1(apartment), 2(house),"
+ " or 3(dorm).","Dwelling Type", JOptionPane.QUESTION_MESSAGE);
homeNum = Integer.parseInt(home);
if(!(homeNum == 1) && !(homeNum == 2) && !(homeNum == 3))
{
JOptionPane.showMessageDialog(null, "The value for dwelling type "
+ "must be 1(apartment), 2(house), or 3(dorm)", "Dwelling"
+ "Type Error", JOptionPane.ERROR_MESSAGE);
}
}
while(homeNum < 0 || homeNum > 3);
return homeNum;
}
As it is, you are returning from the method at the end of the first loop iteration. You might also want to catch the potential NumberFormatException that can be thrown by the parseInt call.
Also, be aware that this will allow 0 to be entered. Perhaps that's by design; perhaps an oversight. I can't tell.
Welcome to Java:
do
{
...
return homeNum;
}
while(homeNum < 0 || homeNum > 3);
In Java, the following instruction all finish the current statement: the code after will never be executed or you'll get an error. You must move the return outside the loop for it to work correctly (or as intended):
do
{
...
}
while(homeNum < 0 || homeNum > 3);
return homeNum;
return : when you return a value, like in return homeNum, you exit the method in which you are.
continue : when you continue, you'll go to next iteration; this only works in a loop.
break : when you break, you'll end the execution of a loop or a switch statement. For instance, if you had put break; instead of return h omeNum; the loop would have ended here.
throw new Exception("Foobar") : when you throw an error, it will exit the current try .. catch block method up one matching the exception kind.
As an example of break, throw and continue:
public static int getHome()
{
int n = -1;
for (;;) { // infinite loop powered !
try {
String home = JOptionPane.showInputDialog(null,"Enter 1(apartment), 2(house),"
+ " or 3(dorm).","Dwelling Type", JOptionPane.QUESTION_MESSAGE);
int homeRun = Integer.parseInt(home);
if(homeNum != 1 && homeNum != 2) && homeNum != 3) {
// note: this is an example. You should NEVER use exception in these case
throw new IllegalArgumentException("Damn!");
}
n = homeRun;
break;
} catch (NumberFormatException|IllegalArgumentException e) {
JOptionPane.showMessageDialog(null, "The value for dwelling type "
+ "must be 1(apartment), 2(house), or 3(dorm)", "Dwelling"
+ "Type Error", JOptionPane.ERROR_MESSAGE);
continue;
}
}
return n;
}
This is an ugly example showing you the four instructions.
Throwing an exception in this case is bad practise. But it'll go to the catch block because it catches the NumberFormatException (from Integer.parseInt) and the thrown IllegalArgumentException.
The break could be replaced by a return homeRun;
The continue is useless in this case because there is nothing left after the try catch block.
Beside, if you are learning Java, you should perhaps read that because I think you are not doing think right. There exists GUI components that does the cumbersome work of handling input conversion for you.
Or even, instead of JOptionPane, you should rely on System.in and Scanner: it is pretty strange to execute a code in a terminal/console, then being asked in a window on some input, to then come back in the terminal/console.

Categories

Resources