Battleship Game-Exceptions - java

I'm doing a java program for an assignment, and one of the exceptions are that the user cannot input a value for a row or column that does not exist. i.e If the board was 5x7 and the user entered a column of value 10 the screen would print "Error: Invalid column" . However i'm unsure how to do this final exception and i need to submit it today. If anyone could help i'd really appreciate it! Here is my code for the makeGuess() function:
public void makeGuess(){
//guesses is for keeping track of your guesses
boolean cont=true;
int rowGuess;
int columnGuess;
do{
System.out.println("Enter a row to guess >");
rowGuess = (input.nextInt()-1);
if(rowGuess<=0){
System.out.println("You did not enter a positive Integer.Please try again");
cont=false;}
else{
cont=true;}
}
while (cont==false);
do{
System.out.println("Enter a column to guess >");
columnGuess = (input.nextInt()-1);
if(columnGuess <=0){
System.out.println("You did not enter a positive integer.Please try again");
cont=false;
} else{
cont=true;
}
}while(cont==false);

Assuming that the rest of your code works, you could simply alter your if statements to ensure the entry is valid.
Using the OR operator ||:
if (columnGuess <= 0 || columnGuess >= 10){
System.out.println("Error: invalid Column");
}

just as you have an if statement to test if the number is too small you also need to test if it is too big
public void makeGuess(){
//guesses is for keeping track of your guesses
boolean cont=true;
int rowGuess;
int columnGuess;
do{
System.out.println("Enter a row to guess >");
rowGuess = (input.nextInt()-1);
if(rowGuess<=0){
System.out.println("You did not enter a positive Integer.Please try again");
cont=false;
}else if(rowGuess>7){
System.out.println("You did not enter a small enough Integer.Please try again");
cont=false;
}else{
cont=true;
}
}while (cont==false);
do{
System.out.println("Enter a column to guess >");
columnGuess = (input.nextInt()-1);
if(columnGuess <=0){
System.out.println("You did not enter a positive integer.Pleasetry again");
cont=false;
}else if(columnGuess>5){
System.out.println("You did not enter a small enough Integer.Please try again");
cont=false;
} else{
cont=true;
}
}while(cont==false);

A better way to do this in my experience is to create your own exception
public class BadMoveException extends Exception {
BadMoveException(Exception ex) {
super(ex);
}
BadMoveException(String ex) {
super(ex);
}
}
Make makeGuess throw BadMoveException, and then for any of the invalid moves the user can make, you can create a BadMoveException with that, and print it in the catch { } block outside of makeGuess
while (!gameOver) {
try {
makeGuess();
}
catch (BadMoveException ex) {
System.out.println("You tried to make an invalid move:" + ex.getMessage());
}
}

Related

Error handling for integer from user isn't working

I'm making a small word game which requires the user to choose from options 1 to 3, 1 and 2 being a game and 3 being exit. I have the error handling set for the correct integer but not sure why the program crashes when the user inputs something thats not an integer.
import java.util.Scanner;
public class Small_Programming_Assignment {
public static void main(String[] args) {
getSelection();
substringProblem();
pointsProblem();
}
public static void getSelection() {
Scanner sc = new Scanner(System.in);
System.out.println("");
System.out.println("Welcome to the Word Games program menu.");
System.out.println("Select from one of the following options.");
System.out.println("1. Substring problem.");
System.out.println("2. Points problem.");
System.out.println("3. Exit.");
System.out.println("Enter your selection: ");
int choice = sc.nextInt();
if (choice == 1) {
substringProblem();
}
else if (choice == 2) {
pointsProblem();
}
else if (choice == 3) {
System.out.println("Goodbye!");
System.exit(0);
}
else if (!sc.hasNextInt() ) {
System.out.println("Invalid option. Try again.");
getSelection();
} else {
System.out.println("Invalid option. Try again.");
getSelection();
}
}
public static void substringProblem() {
System.out.println("Substring Problem");
getSelection();
}
public static void pointsProblem() {
System.out.println("Points Problem");
getSelection();
}
}
I'm trying to uses (!sc.hasNextInt() ) but it seems the program crashes before reaching this.
As far as I see, whenever I type in a value that's not an Integer, the program throws a Runtime Exception called InputMismatchException.
According to Oracle's Java documentation:
Thrown by a Scanner to indicate that the token retrieved does not match the pattern for the expected type, or that the token is out of range for the expected type.
The program doesn't reach your "Invalid option. Try again." statement, because the exception is thrown directly after the user input, which means, you can't provide anything other than an integer through Scanner's nextInt() method.
What you could do, if you still want to use this method, would be placing it in a try/catch statement, something like below:
int choice = 0;
try {
choice = sc.nextInt();
}
catch(InputMismatchException e) {
System.out.println("Invalid option. Try again.");
getSelection();
}
if (choice == 1) {
substringProblem();
}
else if (choice == 2) {
pointsProblem();
}
else if (choice == 3) {
System.out.println("Goodbye!");
System.exit(0);
}
else {
System.out.println("Invalid option. Try again.");
getSelection();
}
This should do the job. Now, whenever a user is typing something that cannot be parsed as an Integer, the runtime exception is thrown, is caught, so the program enters the catch block, outputs "Invalid option. Try again." and "re"-calls getSelection().

How to solve the else/if problems in password input?

I wrote a program that users can login. Below u see some codes that I wrote for the password input but the second if of them does not work properly.
Please help me to find the problem. Why it does not work?
import java.util.Scanner;
public class Password {
public static void main(String[] args) {
Scanner passwordInput = new Scanner(System.in);
System.out.print("Please enter your password: ");
int builtInPassword = 1254;
if (passwordInput.hasNextInt() && passwordInput.nextInt() == builtInPassword) {
System.out.println("Your password is correct.");
} else if (passwordInput.hasNextInt() && passwordInput.nextInt() != builtInPassword) {
System.out.println("The password entered is incorrect");
} else {
System.out.println("Sorry, please enter the right format");
}
}
}
The problem is that you call nextInt() in all ifs. This way you basically wait for another input each time you call passwordInput.nextInt().
Try to save the user input and then check it for the password. Something like:
if (passwordInput.hasNextInt()) {
int pass = passwordInput.nextInt();
if (pass == builtInPassword) {
System.out.println("Your password is correct.");
} else {
System.out.println("The password entered is incorrect");
}
} else {
System.out.println("Sorry, please enter the right format");
}
I am writing without a compiler here so I am not sure it will compile properly but you can get the idea ;)
scanner.hasNextInt() check the value is int or not, but its not consume the value. but in your code "pasword not matching" case scanner will go through two ifs and two hasNextInt() callings. therefore in second if it will return false value.
you can correct and optimize you code using exceptions as follow.
try {
if(passwordInput.nextInt()==builtInPassword){
System.out.println("Your password is correct.");
}else{
System.out.println("The password entered is incorrect");
}
} catch (InputMismatchException e) {
System.out.println("Sorry, please enter the right format");
}
As noted by others, the problem is that you are calling nextInt() twice, and it tries to get a new int each time. The simplest solution would be to change your first else to else if (passwordInput.hasNextInt()) {, as you already know the second condition (the password is wrong) holds from the fact that the if failed. However, I would advise restructuring your code so that there is no need to call hasNextInt twice either, as this seems cleaner:
if (passwordInput.hasNextInt()) {
if (passwordInput.nextInt() == builtInPassword) {
System.out.println("Your password is correct.");
} else {
System.out.println("The password entered is incorrect.");
}
} else {
System.out.println("Sorry, please enter the right format");
}
I you need a while loop.
while (passwordInput.nextInt() != builtInPassword) {
System.out.println("Incorrect password");
}
System.out.println("Correct password!");

JAVA I don't understand Try-catch

This is my first time here. I'm starting to learn how to code, so I honestly hope this question I have is not something I can find over here! (I promise I searched for a while, but since I'm a noob in this topic, I didn't found anything understandable for me in order to resolve my doubt).
I'm doing a simple game in JAVA, in which the program generates a random number and the player has to guess the number generated.
When the player enters a number, the game displays a hint, saying if it is higher or lower than the number generated randomly.
The program itself works fine if you enter just numbers, but I want to add a try-catch statement to handle bad user input.
I tried using the statement as I show in my code, but I can't understand why it's not working properly, because when I enter something different of a number, the exception is catched and it prints on console the System.out.println(), but program terminates when this happens.
I would like to try-catch just to get the exception of entering not a number without terminating the program every time the exception is catched.
How can I fix this?
Thanks a lot for your help!
import java.util.Scanner;
public class HiLo {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in); //Creates Scanner object to read from keyboard
String playAgain = ""; //if == y, game restarts
try {
do {
// Create a random number for the user to guess
int theNumber = (int)(Math.random() * 100 + 1);
//System.out.println(theNumber); //Uncoment this in case we want to know the number (for testing).
int guess = 0; //Number entered by the player
int count = 0; //Number of tries of guessing the number
while(guess != theNumber){
System.out.println("Guess a number between 1 and 100:");
guess = scan.nextInt(); //Reads the number typed on the keyboard by the player
count++; //Plus 1 every time a number is entered
System.out.println("You entered " + guess +".");
if(guess < theNumber) { //If number entered is smaller
System.out.println("The number is bigger" + ", try again!");
System.out.println("Number of tries: " + count);
} else if(guess > theNumber) { //If number entered is bigger
System.out.println("The number is smaller" + ", try again!");
System.out.println("Number of tries: " + count);
} else { //If both previous cases are false
System.out.println("Congratulations! You've found the number!");
}
}
//Once guess == theNumber
System.out.println("Number of tries: " + count);
System.out.println("Play again? (y/n)");
playAgain = scan.next(); //Reads the String entered from keyboard by the player
}
while(playAgain.equalsIgnoreCase("y")); //If player enters y, start again.
//Otherwise
System.out.println("Thank you for playing! Goodbye :)");
} catch (Exception e) {
System.out.println("Incorrect entering! Please enter a number between 1 and 100.");
}
scan.close(); //Close scanner
} //Close main
} //Close class
place try-catch inside the while loop and reinstantiate the scanner object (scan = new Scanner(System.in) inside the catch block.
while (guess != theNumber) {
try {
System.out.println("Guess a number between 1 and 100:");
guess = scan.nextInt(); // Reads the number typed on the
// keyboard by the player
count++; // Plus 1 every time a number is entered
System.out.println("You entered " + guess + ".");
if (guess < theNumber) { // If number entered is smaller
System.out.println("The number is bigger" + ", try again!");
System.out.println("Number of tries: " + count);
} else if (guess > theNumber) { // If number entered is
// bigger
System.out.println("The number is smaller" + ", try again!");
System.out.println("Number of tries: " + count);
} else { // If both previous cases are false
System.out.println("Congratulations! You've found the number!");
}
} catch (Exception e) {
System.out.println("Incorrect entering! Please enter a number between 1 and 100.");
scan = new Scanner(System.in);
}
}
You need to understand the working of the try-catch block. You don't need to surround the entire code within try. Just put that part of the code which causes an exception. So, in your case just surround guess = scan.nextInt(); with try and then catch an exception. Because, here this statement raises an exception when the input is not an integer. This way you can ensure that the user input is valid for each iteration of the while(guess != theNumber) loop.
Edit_1:
I removed the try-catch blocks from your code and added the following & it works fine for me:
try{
guess = scan.nextInt();} //Reads the number typed on the keyboard by the player
catch (InputMismatchException e){
System.out.println("Incorrect entering! Please enter a number between 1 and 100.");
scan.nextLine();
continue;
}

Do-while loop not waiting for user input?

I'm sure this is something simple that I just can't spot, I have a do while loop prompting the user for an array size, which will be used for the rest of the program. If the user enters the right input, the program continues and works fine, but if the user enters the wrong input...
public static void main(String[] args)
{
// user enters up to 20 double values, stored in an array, user should enter 99999 to quit entering numbers. If user has not entered any numbers yet
// display an error message, otherwise, display each entered value and it's distance from the average
Scanner keyboard = new Scanner(System.in);
int arraySize = 0;
boolean isValid = false;
do
{
isValid = true;
arraySize = 0; // reset these values at start of each loop.
System.out.println("Enter an array size.");
try {
arraySize = keyboard.nextInt();
}
catch(NegativeArraySizeException mistake) {
System.out.println("Do not enter a negative number for the arrays size.");
System.out.println();
isValid = false;
}
catch(InputMismatchException mistake) {
System.out.println("Make sure to enter a valid number.");
System.out.println();
isValid = false;
}
} while (isValid == false);
If the user enters an invalid input, such as "red", the catch block kicks in and prints "Make sure to enter a valid number." and "Enter an array size." over and over without giving the user a chance to actually enter any input. I figured resetting the arraySize variable would fix it, but it doesn't. I guess the keyboard buffer has stuff in it, but no combination of empty printlns has worked so far.
I've heard that Exceptions shouldn't be used to validate user input. Why is that?
Regardless, it's not relevant to this question, as it is an exercise in Exception handling.
Without using isValid boolean variable and make simple code for input.
int arraySize = 0;
do {
System.out.println("Enter a valid array size.");
try {
arraySize = Integer.valueOf(keyboard.nextLine());
if (arraySize < 0) throw new NegativeArraySizeException();// for negative arry size
break;// loop break when got a valid input
} catch (Exception mistake) {
System.err.println("Invalid input: " + mistake);
}
} while (true);
You can add a keyboard.nextLine(); in the event of exception and it should resolve the issue.
try {
arraySize = keyboard.nextInt();
}
catch(NegativeArraySizeException mistake) {
System.out.println("Do not enter a negative number for the arrays size.");
System.out.println();
isValid = false;
keyboard.nextLine();
}
catch(Exception mistake) {
System.out.println("Make sure to enter a valid number.");
System.out.println();
isValid = false;
keyboard.nextLine();
}
Please see if this fix works for you. Scanner has a problem when you are trying to get the string from nextInt function. In this I have fetched the string and parsed to Integer and then handled the Number format exception
public static void main(String[] args) {
// user enters up to 20 double values, stored in an array, user should enter 99999 to quit entering numbers. If user has not entered any numbers yet
// display an error message, otherwise, display each entered value and it's distance from the average
Scanner keyboard = new Scanner(System.in);
int arraySize = 0;
boolean isValid = false;
do {
isValid = true;
arraySize = 0; // reset these values at start of each loop.
System.out.println("Enter an array size.");
try {
arraySize = Integer.parseInt(keyboard.next());
} catch (NegativeArraySizeException mistake) {
System.out.println("Do not enter a negative number for the arrays size.");
System.out.println();
isValid = false;
} catch (InputMismatchException mistake) {
System.out.println("Make sure to enter a valid number.");
System.out.println();
isValid = false;
} catch (NumberFormatException nfe) {
System.out.println("Make sure to enter a valid number.");
System.out.println();
isValid = false;
}
} while (isValid == false);
}
mmuzahid is almost there. But I added a way of checking negative number as well. Try this
Scanner keyboard = new Scanner(System.in);
int arraySize = 0;
boolean isValid = false;
do {
System.out.println("Enter a valid array size.");
try {
arraySize = Integer.valueOf(keyboard.nextLine());
if (arraySize < 0) {
System.out.println("Make sure to enter a valid positive number.");
} else {
break;
}
} catch (Exception mistake) {
System.out.println("Make sure to enter a valid number. Error:" + mistake);
}
} while (true);
Use keyboard.nextLine() and NumberFormatException
do {
// more code
try {
arraySize = Integer.valueOf((keyboard.nextLine()));
} catch (NegativeArraySizeException mistake) {
// more code
isValid = false;
} catch (InputMismatchException mistake) {
// more code
isValid = false;
} catch (NumberFormatException mistake) {
// more code
isValid = false;
}
} while (isValid == false);

Why does my program print out the exception statement endlessly give bad user input?

Ive no idea if my title made sense but here is the code ©
import java.util.InputMismatchException;
import java.util.Scanner;
public class Gussing {
public static void theGame(Scanner input){
int randomNum= (int)(Math.random()*101);//randomizes a number between 0-100 inclusive of both
System.out.println(randomNum); //for debugging purposes
int attemptCounter = 0; //counts how many attempts the user make
System.out.print("Welcome to the guess-the number game! Enter your guess: ");
while(true){
System.out.println("here is bad input");
try{
System.out.println("here is after the bad input");
int userInput= input.nextInt();
if (userInput==randomNum) //when usr input and generated random number are equal we print how many attempts
{
attemptCounter++;
System.out.println("Congrats you made the right guess after "+ attemptCounter + " attempts!");
break;
}
if(userInput<randomNum){
attemptCounter++;
System.out.print("Too low! Try again: ");
}
else {
attemptCounter++; //else clause does the opposite of if clause
System.out.print("Too high! Try again: ");
}
}
catch( Exception e){
System.out.println("Invalid input");
}
}
}
public static void main(String[] args){
Scanner input = new Scanner (System.in);
theGame (input);
System.out.println("Play again? (Y/N)");
try{
char answer=input.next().toLowerCase().charAt(0);
//toLowerCase method so that N =n = no !
if (answer =='y') theGame (input);
else if (answer =='n') System.out.println("Good bye");
input.close(); //no more input data
}
catch(Exception e){
System.out.println("invalid input");
}
}
}
so when the user types in the wrong type i.e not int it prints out invalid input. This is however not the problem the problem is that it prints that out infinitely. I tried adjusting the try catchblocks but it didnt help at all
nextInt doesnt remove non-integer data from the input buffer so it gets recycled indefinitely unless the data is consumed. In this case an InputMismatchException is thrown by the method so you could write your exception block as
} catch (InputMismatchException e) {
System.out.println("Invalid input " + input.nextLine());
}

Categories