How to make my program have an outofbounds exception - java

I am trying to catch an outofbounds exception in my program that creates a random number from 1 to 50 and the user guesses that number. The problem that I am facing is that whenever I enter a number that is past the maximum it doesn't catch it as an exception and displays the appropriate message but instead displays a different message.
This is what I have currently
Scanner in = new Scanner(System.in);
int count = 0, ran, min = 1, max = 50;
int ent = 0;
ran = (int)(Math.random()*(max-min)) + min;
System.out.println("Guess a number from 1 to 50.");
try{
do{
ent = in.nextInt();
count++;
if(ent > ran){
System.out.println("Too high. Try again.");
}else if(ent < ran){
System.out.println("Too low. Try again.");
}
}while(ent!=ran);
}
catch(IndexOutOfBoundsException ex){
System.out.println("Guess a number from 1 to 50!");
}
catch(InputMismatchException ex){
System.out.println("Invalid input");
}
I also want to continue the program even after catching an exception but whenever I try to change it the result ends in an infinite loop
boolean done = false;
while(!done){
System.out.println("Guess a number from 1 to 50.");
try{
ent = in.nextInt();
count++;
if(ent > ran){
System.out.println("Too high. Try again.");
}else if(ent < ran){
System.out.println("Too low. Try again.");
}
done = true;
}
catch(IndexOutOfBoundsException ex){
System.out.println("Guess a number from 1 to 50!");
}
catch(InputMismatchException ex){
System.out.println("Invalid input");
}
}
this is what I tried to do

You should not employ Exceptions for flow control - use a loop with a if-condition that makes sense. You can bake it into the while-loop condition but in this case the return short-circuits the loop if the guess is valid.
public int getGuess(Scanner in) {
while (true) {
System.out.printf("Enter a value between %d and %d", min, max).println();
int guess = in.nextInt();
if (guess < min || guess > max) {
System.out.printf("Guess must be between %d and %d, try again", min, max).println();
} else {
return guess;
}
}
}

Related

I can't use NumberFormatExeption. The program should continue even if the user input a string or non-number

Guessing the number
import java.util.*;
public class LabExer5A
{
public static void main(String args[])
{
Scanner Input = new Scanner (System.in);
System.out.println("Guess a number between 1 and 50");
int JPS_Guess = Input.nextInt();
int JPS_CorrectNum = 25;
int JPS_NextGuess;
do
{
try
{
if (JPS_Guess == JPS_CorrectNum)
{
System.out.println("You got it in ");
}
else if (JPS_Guess < JPS_CorrectNum && JPS_Guess >= 1)
{
System.out.println("Too low. Try again.");
JPS_NextGuess = Input.nextInt();
JPS_Guess = JPS_NextGuess;
}
else if (JPS_Guess > JPS_CorrectNum && JPS_Guess <= 50)
{
System.out.println("Too High. Try again.");
JPS_NextGuess = Input.nextInt();
JPS_Guess = JPS_NextGuess;
}
else if(JPS_Guess < 1 || JPS_Guess > 50)
{
throw new InputMismatchException();
}
}
catch(InputMismatchException e)
{
System.out.println("Invalid value. Please enter a number between 1 and 50: ");
JPS_NextGuess = Input.nextInt();
JPS_Guess = JPS_NextGuess;
}
catch (NumberFormatException ex)
{
System.out.println("Error - Enter Numerical Values Only");
JPS_NextGuess = Input.nextInt();
JPS_Guess = JPS_NextGuess;
}
}
while (JPS_Guess != JPS_CorrectNum);//will rerun the program until the user guess the correct number
}
}
}
}
I'm not sure where I made the mistake. Either the use of the throw catch or maybe because of the way I rerun the program. I'm pretty new to using exception and try-catch Please help and be kind. Thank you.
nextInt() actually throws InputMismatchException when you input other data type so you can directly use the catch for InputMismatchException and you should add Input.next() so that the scanner will take in the non integer input
Another thing is that Input.nextInt() should always be inside the try/catch. In your code, the exception will not be catched for the first input and after you input any wrong value.
catch(InputMismatchException e)
{
System.out.println("Invalid value. Please enter a number between 1 and 50: ");
JPS_NextGuess = Input.nextInt();
JPS_Guess = JPS_NextGuess;
}
I have modified your code to be simpler. I suggest you use boolean to keep track of whether the number is guessed so you don't have to interchange the guess. Also, good indentation formatting helps reading.
import java.util.*;
public class LabExer5A
{
public static void main(String args[])
{
Scanner Input = new Scanner (System.in);
System.out.println("Guess a number between 1 and 50");
int JPS_CorrectNum=25;
boolean isGuessed=false;
do
{
try
{
int JPS_Guess = Input.nextInt();
if (JPS_Guess == JPS_CorrectNum)
{
System.out.println("You got it in ");
isGuessed=true;
}
else if (JPS_Guess < JPS_CorrectNum && JPS_Guess >= 1)
{
System.out.println("Too low. Try again.");
}
else if (JPS_Guess > JPS_CorrectNum && JPS_Guess <= 50)
{
System.out.println("Too High. Try again.");
}
else if(JPS_Guess < 1 || JPS_Guess > 50)
{
throw new InputMismatchException();
}
}
catch(InputMismatchException e)
{
System.out.println("Invalid value. Please enter a number between 1 and 50: ");
Input.next();
}
}
while (!isGuessed);//will rerun the program until the user guess the correct number
}
}

How to make a exception that inform the user that the number they input is out of range?

We were given a task by my teacher that will ask user for an input of an integer 1 to 50, I've nearly completed my code but the only thing missing is a catch on informing the user if they input more than 50. Can you help me what is the missing in my code. I've read my handouts there is no such thing as an Exception that limiting a certain amount of integer or whatsoever.
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int answer = 28;
int attempts = 0;
boolean condition = false;
System.out.println("Guess a Number 1 - 50:");
do {
condition = true;
try {
int input = scan.nextInt();
scan.nextLine();
if(input > answer) {
System.out.println("Too Big");
System.out.println(); //Spacing
System.out.println("Guess a Number 1 - 50:");
attempts++;
} else if (input < answer) {
System.out.println("Too Small");
System.out.println(); //Spacing
System.out.println("Guess a Number 1 - 50:");
attempts++;
} else {
int totalA = attempts + 1;
System.out.println(); //Spacing
System.out.println("Congratulations! "+ "You attempted " + totalA + " times." );
}
} catch (InputMismatchException e) {
System.out.println("Numbers only");
System.out.println(); //Spacing
System.out.println("Guess a Number 1 - 50:");
condition = true;
scan.nextLine();
}
} while(condition);
}
I think it is very important that you know that you can create your own Exception classes that have their specific messages and uses.
For example:
public class NumberTooHighException extends Exception {
public NumberTooHighException() {
super("The number inputted is wayyyy to high...");
}
}
And then you can use your Exception as any other:
if(input > 50)
{
throw new NumberTooHighException(); // Here you throw it...
}
And if you wanna catch it, you wrap your code in a try-catch block. More on that here.
But as the comments hint:
An exception is a way of having a method tell the caller of that
method that something went wrong
So try to avoid using them for specific use cases (as this one for example). Even though yours is homework/schoolwork.
So in order to throw an exception from your code, you need to do this ...
if(input > answer) {
...
throw new IllegalArgumentException("Argument is too big");
...
} else if (input < answer) {
...
throw new IllegalArgumentException("Argument is too small");
...
} else {
...
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int answer = 28;
int attempts = 0;
int maxNumber = 50;
boolean condition = false;
System.out.println("Guess a Number 1 - 50:");
do {
condition = true;
try {
int input = scan.nextInt();
scan.nextLine();
if (input > maxNumber){
throw new InputMismatchException();
}else if(input > answer) {
System.out.println("Too Big");
System.out.println(); //Spacing
System.out.println("Guess a Number 1 - 50:");
attempts++;
} else if (input < answer) {
System.out.println("Too Small");
System.out.println(); //Spacing
System.out.println("Guess a Number 1 - 50:");
attempts++;
} else {
int totalA = attempts + 1;
System.out.println(); //Spacing
System.out.println("Congratulations! "+ "You attempted " + totalA + " times." );
}
} catch (InputMismatchException e) {
System.out.println("Numbers only");
System.out.println(); //Spacing
System.out.println("Guess a Number 1 - 50:");
condition = true;
scan.nextLine();
}
} while(condition);
}

InputMismatchException in Java replacing while loop

In my task I need to put InputMismatchException when user tries to enter some values. User get some numbers from 1 to some number (simptoms.lenght).
int number=0;
do{
System.out.printf("Choose %d simptoms: \n", number+1);
for(int j=0; j< simptomi.length;j++){
System.out.printf("%d. %s %s\n", j + 1, simptoms[j].getName(),
simptoms[j].getValue());
}
System.out.print("Choose: ");
while(!scanner.hasNextInt()){
System.out.println("Please enter number!");
scanner.next();
}
number=scanner.nextInt();
scanner.nextLine();
if(number<0 || number> simptoms.length){
System.out.println("Error, choose again");
}
}while(number<0 || number> simptoms.length);
After this code I tried to do this:
instead of while(!scanner.hasNextInt()) I tried with try and I get this message:
Declaration, final or effectively final variable expected.
Is this the right way of replacing while loop or I should try to add something else.
I'm thinking about boolean = false and somehow try with that but I don't understand how to implement it properly.
I tried this:
try{
number=scanner.nextInt();
scanner.nextLine();
}
catch (InputMismatchException ex){
System.out.println("Please, enter number!");
}
Try it out! hope it helps!
try {
do {
number = scanner.nextInt();
if (!Character.isAlphabetic(number)) {
if (number > simptoms.length) {
System.out.println("Error, choose again");
System.out.println("Please enter number!");
}
}
} while (number != -1);
} catch (InputMismatchException e) {
System.out.println("Enter number");
}

checking input for positive number

So for my programming assignment the user has to enter the number of grades, but we have to check the input and return the proper error. The number has to be a positive number, and the program needs to differ between the error and give the proper response and loop it back until the right number is inputed. I got the error checking part but I'm having trouble getting the program to continue to the next part. any help would be appreciated
do {
System.out.println("Enter number of grades");
if (input.hasNextInt()){
numGrade = input.nextInt();
if (numGrade < 0){
System.out.println("Your number of grades needs to positive! Try again");
count1++;
continue;
}
}
else{
System.out.println("You did not enter a number! Try again");
count1++;
input.next();
continue;
}
}while (count1 > 0);
Try this,
//use a boolean to tell the loop to continue or not
boolean cont = true;
do {
System.out.println("Enter number of grades");
if (input.hasNextInt()){
numGrade = input.nextInt();
//I assume 0 is a valid response (not a negative int)
if (numGrade <= 0){
System.out.println("Your number of grades needs to positive! Try again");
continue;
}
else {
cont = false;
System.out.println("Your input is valid! Value entered is " + numGrade);
}
}
else {
System.out.println("You did not enter a number! Try again");
input.next();
continue;
}
}
while (cont);

implementing a try/catch block

So I am working on a guessing number game that uses a try/catch block to catch (this is homework). If the user enters a non-integer value or a number that is below or above the given range (in this case 1-10).
But I am having issues understanding/properly placing the try catch block I read on how it works but when I try to implement it into my simple code it just seems to be ignored.
Here is the code
//import statements
import java.util.*; //for scanner class
// class beginning
class Guess {
public static void main(String[] args ) {
//Declare variables area
int secretNumber, guess;
secretNumber = (int) (Math.random() * 10 + 1);
Scanner keyboard = new Scanner(System.in);
// beginning message to user to explain the program
System.out.println("Welcome to my guess a number program!");
System.out.println("Please enter in a number to begin guess what the secret number is(1-10): ");
//Collect inputs from user or read in data here
System.out.println("Enter a guess (1-10): ");
try {
guess = keyboard.nextInt();
if (guess < 1 || guess > 10){
}
} catch (InputMismatchException e) {
guess= keyboard.nextInt();
System.out.println("Not a valid integer");
}
//Echo input values back to user here
//main code and calculations to do
do {
if (guess < 1 || guess > 10) {
System.out.println("Your guess is not in the corre try again.");
guess = keyboard.nextInt();
}
if (guess == secretNumber) {
System.out.println("Your guess is correct. Congratulations!");
guess = keyboard.nextInt();
} else if (guess < secretNumber) {
System.out
.println("Your guess is smaller than the secret number.");
guess = keyboard.nextInt();
} else if (guess > secretNumber) {
System.out
.println("Your guess is greater than the secret number.");
guess = keyboard.nextInt();
}
} while (guess != secretNumber);
//End program message
System.out.println();
System.out.println("Hope you enjoyed using this program!");
}// end main method
}// end class
It doesn't display "Your guess is correct. Congratulations!" when you guess the right number.
Am I implementing the try catch block correctly? If not how do I and can it be explained so I can do the second one where it catches the float, string and anything not a int.
what it does do
it correctly randomizes from 1-10
the program does check to see if it is within the given range
EDIT
below is the updated code my only issue I have with it now is that I can't figure out how to apply another catch if a user just hits enter without entering anything I assume I'd need to take the input from user turn it into a string then compare?
//import statements
import java.util.*; //for scanner class
// class beginning
public class Guess {
public static void main(String[] args ) {
//Declare variables area
int guess, secretNumber = (int) (Math.random() * 10 + 1), lowGuess,highGuess;
Scanner keyboard = new Scanner(System.in);
// beginning message to user to explain the program
System.out.println("Welcome to my guessing number program!");
System.out.println("Please enter in a number to start guessing(enter in a number between 1-10): ");
//main code and calculations to do
guess = 0;
lowGuess = 0;
highGuess = 11;
do {
try {
guess = keyboard.nextInt();
if (guess < 1 || guess >10){
System.out.println("Your guess is not in the correct range try again.");
}
else if(guess == secretNumber){
System.out.println("Your guess is correct. Congratulations!");
}
else if(guess < secretNumber && guess <= lowGuess){
System.out.println("The number you entered is either the same entered or lower please re-enter");
}
else if (guess < secretNumber && guess > lowGuess){
lowGuess = guess;
System.out.println("Your guess is smaller than the secret number.");
}
else if ( guess > secretNumber && guess >= highGuess ){
System.out.println("The number you entered is either the same entered or higher please re-enter");
}
else if (guess > secretNumber && guess < highGuess){
highGuess = guess;
System.out.println("Your guess is greater than the secret number.");
}
} catch (InputMismatchException e) {
System.out.println("Not a valid input please re-enter");
keyboard.next();
guess = 0;
}
} while (guess != secretNumber);
//End program message
System.out.println();
System.out.println("Hope you enjoyed using this program!");
}// end main method
}// end class
What do you want to do here ?
if (guess < 1 || guess > 10) {
}
You should try something like this :
public class Guess {
static int guess, secretNumber = (int) (Math.random() * 10 + 1);
static Scanner keyboard = new Scanner(System.in);
public static void main(String[] args ) {
do {
try {
guess = keyboard.nextInt();
if (guess < 1 || guess >10){
System.out.println("Your guess is not in the corre try again.");
}
if(guess == secretNumber){
System.out.println("Your guess is correct. Congratulations!");
}
else if (guess < secretNumber){
System.out.println("Your guess is smaller than the secret number.");
}
else if (guess > secretNumber){
System.out.println("Your guess is greater than the secret number.");
}
} catch (InputMismatchException e) {
System.out.println("Not a valid integer");
}
} while (guess != secretNumber);
}
}
EDIT : You have to put a piece of code which could maybe throw an exception, in the scope of the try block. It is state of the art to know which part of the code to put in the try block (not too much nor too less).
in-between the try and catch you have your main code/calculations to
do and then you close it off and end with the catch to see if after
all that if what was entered was valid?
You could always catch the exceptions at top level like you're saying here, but in practice that's not the way to do it. Because when an exception occurs and you don't catch it there will be a process called stack unwinding.
It's really important to understand how stack unwinding works in order to understand what's happening.
You can find information about how this process works here : Explanation of stack unwinding. It explains stack unwinding in C++ but I expect it to be (exactly) the same in Java.
This is another approach, but using Exceptions. Please, read this page to understand how try/catch block works.
//import statements
import java.util.*; //for scanner class
// class beginning
class Guess {
public static void main(String[] args ) {
//Declare variables area
int secretNumber, guess;
secretNumber = (int) (Math.random() * 10 + 1);
Scanner keyboard = new Scanner(System.in);
// beginning message to user to explain the program
System.out.println("Welcome to my guess a number program!");
System.out.println("Please enter in a number to begin guess what the secret number is(1-10): ");
//Collect inputs from user or read in data here
//main code and calculations to do
do {
System.out.println("Enter a guess (1-10): ");
try {
guess = keyboard.nextInt();
if (guess < 1 || guess > 10){
throw new Exception("Number must be between 1 and 10");
}else if(guess == secretNumber){
throw new Exception("YOU WIN");
}
else if (guess < secretNumber){
throw new Exception("NUMBER IS +");
}
else if (guess > secretNumber){
throw new Exception("NUMBER IS -");
}
} catch (InputMismatchException e)
{
System.println("mustbeanumber");
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
} while (guess != secretNumber);
//End program message
System.out.println();
System.out.println("Hope you enjoyed using this program!");
}// end main method
}// end class`

Categories

Resources