Java try catch not handling IndexOutOfBoundsException - java

I was having some problem when try to try catch the IndexOutOfBoundsException for a List in Java. So I declared my list with 2 elements as:
List<String> list = new ArrayList<>(Arrays.asList("item1", "item2"));
Then I tried to do a try catch:
do {
for (int i = 0; i < list.size(); i++) {
System.out.print("(" + (i + 1) + ")" + list.get(i));
}
System.out.println(" ");
try{
option = sc.nextInt();
} catch (IndexOutOfBoundsException e){
System.out.println("Invalid option");
sc.next();
continue;
} catch (InputMismatchException e) {
System.out.println("Option input mismatch.");
sc.next();
continue;
}
sc.nextLine();
if (option == 1) {
System.out.print("Enter name: ");
// scanner takes in input
} else if (option == 2) {
System.out.print("Enter desc: ");
// scanner takes in input
}
type = list.get((option - 1));
} while (option <= 0 || option >= 3);
However, when I entered anything larger than 2 for option, it threw me IndexOutOfBounds exception but I thought I did a try catch for it already?
Thanks in advance.

do {
for (int i = 0; i < list.size(); i++) {
System.out.print("(" + (i + 1) + ")" + list.get(i));
}
System.out.println(" ");
try {
option = sc.nextInt();
} catch (IndexOutOfBoundsException e) {
System.out.println("Invalid option");
sc.next();
continue;
} catch (InputMismatchException e) {
System.out.println("Option input mismatch.");
sc.next();
continue;
}
sc.nextLine();
if (option == 1) {
System.out.print("Enter name: ");
// scanner takes in input
} else if (option == 2) {
System.out.print("Enter desc: ");
// scanner takes in input
}
try {
type = list.get((option - 1));
} catch (IndexOutOfBoundsException e) {
System.out.println("Invalid option");
option=3;
}
} while (option <= 0 || option >= 3);
I have added new try-catch at type = list.get((option - 1));
To force user re-input option, I will set option to 3 at the catch cause

You are not going to catch the exception if you don't use an invalid value to call the list.
ArrayList<String> list = new ArrayList<>(Arrays.asList("item1", "item2"));
Scanner sc = new Scanner(System.in);
int option;
try {
option = sc.nextInt();
System.out.println(list.get(option));
} catch (IndexOutOfBoundsException e) {
System.out.println("Invalid option");
} catch (InputMismatchException e) {
System.out.println("Option input mismatch.");
}
sc.close();

You also can do it like this, it will loop till you enter a valid value and after a valid value is entered ask for name or whatever(not implemented)
ArrayList<String> list = new ArrayList<>(Arrays.asList("item1", "item2"));
Scanner sc = new Scanner(System.in);
int option = 0;
while(!(option == 1 || option==2) ) {
try {
option = sc.nextInt();
} catch (InputMismatchException e) {
System.out.println("Option input mismatch.");
}
}
System.out.println(list.get(option-1));
sc.close();

Related

Edit ExceptionSample so it can catch exceptions wherein text is entered as String input instead of integer data type input

How to catch an exception if the the input is string instead of integer?
It's confusing me since they used Try, Catch, Finally which looks new to me. Please enlighten me thanks.
import java.util.*;
public class ExceptionSample {
public static void main (String[]args){
Scanner s = new Scanner(System.in);
int dividend, divisor, quotient;
System.out.print("Enter dividend: ");
dividend = s.nextInt();
System.out.print("Enter divisor: ");
divisor = s.nextInt();
try {
quotient = dividend/divisor;
System.out.println(dividend + " / " + divisor + " = " + quotient);
}
catch (ArithmeticException ex) {
System.out.println("Divisor cannot be 0.");
System.out.println("Try again.");
}
finally {
System.out.println("Thank you.");
}
}
}
It would go something like this:
Scanner s = new Scanner(System.in);
int dividend, divisor, quotient;
while (true) {
System.out.print("Enter dividend: ");
try {
dividend = s.nextInt();
}
catch (java.util.InputMismatchException ex) {
System.out.println("Invalid Dividend Entry! Try again...\n");
s.nextLine(); // consume the Enter Key Hit.
continue;
}
break;
}
while (true) {
System.out.print("Enter divisor: ");
try {
divisor = s.nextInt();
if (divisor == 0) {
throw new java.util.InputMismatchException();
}
}
catch (java.util.InputMismatchException ex) {
System.out.println("Invalid Divisor Entry! Try again...\n");
s.nextLine(); // consume the Enter Key Hit.
continue;
}
break;
}
try {
quotient = dividend / divisor;
System.out.println(dividend + " / " + divisor + " = " + quotient);
}
catch (ArithmeticException ex) {
System.out.println("Divisor cannot be 0.");
System.out.println("Try again.");
}
finally {
System.out.println("Thank you.");
s.close();
}
When the Scanner#nextInt() method is used and one or more alpha characters are supplied a InputMismatchException is thrown. We trap this exception and use it to our advantage for validating the numerical input.

If, else if looping problems

so I'm just finishing up my first computer programming class ever and I'm having problems with my main method. I have 2 classes. The first class is homeClass.java and the other class is homeInventory.java. I'm just going to show you some of my homeInventory.java class unless you smarter ppl feel like it's prudent to have my other class. Basically, I'm having a problem with my else if statements. The program runs w/ the if statement, but won't completely run through the other options (else if). I must be missing something pretty apparent but I'll just see what you have to say on it. Thanks in advance!
public static void main(String[] args) {
ArrayList<homeClass> homes = new ArrayList<>();
Scanner scnr = new Scanner(System.in);
int i = 0;
int j = 0;
String option = "";
String answer = "";
String statusAnswer = "";
do {
System.out.println("Menu:");
System.out.println("1. Add a new home.");
System.out.println("2. Remove a home.");
System.out.println("3. Update home sale status.");
System.out.println("4. Exit");
System.out.print("Option chosen: ");
try {
while(true) {
if(scnr.hasNext()) {
option = scnr.next();
break;
}
}
}
catch (NoSuchElementException NSEE) {
continue;
}
catch (Exception excpt) {
excpt.printStackTrace();
System.out.print("Error, non-integer");
break;
}
try {
if(option.equals("1")) {
homes.add(addHome(scnr));
System.out.println("Home added.");
homes.get(i).getListing();
break;
}
else if (option.equals("2")) {
for(j = 0; j < homes.size(); ++j) {
homes.get(i).getListing();
System.out.print("Remove this listing? Y or N: ");
answer = scnr.next();
if (answer.equalsIgnoreCase("Y")) {
homes.get(i).removeListing();
System.out.println("Home removed.");
}
else if (!answer.equalsIgnoreCase("Y")) {
System.out.println("Home not removed. Choose next option.");
}
}
break;
}
else if (option.equals("3")) {
for(j = 0; j < homes.size(); ++j) {
homes.get(i).getListing();
System.out.print("Do you want to change the sale status? Y or N: ");
answer = scnr.next();
if (answer.equalsIgnoreCase("Y")) {
System.out.println("Enter home sale status: ");
statusAnswer = scnr.next();
homes.get(i).setSaleStatus(statusAnswer);
homes.get(i).getListing();
}
}
break;
}
}
catch (Exception excpt) {
excpt.printStackTrace();
System.out.println("Error, option failed.");
}
} while(!option.equals("4"));
System.out.print("Do you want the home information stored in a file? Y or N: ");
answer = scnr.next();
String outputFileName = "C:\\Temporary\\Home.txt";
for (j = 0; j < homes.size(); ++j) {
String listing = homes.get(i).getListing();
if (answer.equalsIgnoreCase("Y")) {
try {
printToFile(listing, outputFileName);
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
System.out.println("File printed to: " + outputFileName);
}
else {
System.out.println("File not printed.");
}
}
scnr.close();
return;
}
}

Try-Catch Exception Handling does not provide the correct response

I'm not sure why when I input anything other than an integer value, the output isn't showing Invalid Format!.
That's the exception handling that I'm trying to achieve. Also, how can I close the Scanner in a finally clause without causing an infinite loop.
class ConsoleInput {
public static int getValidatedInteger(int i, int j) {
Scanner scr = new Scanner(System.in);
int numInt = 0;
while (numInt < i || numInt > j) {
try {
System.out.print("Please input an integer between 4 and 19 inclusive: ");
numInt = scr.nextInt();
if (numInt < i || numInt > j) {
throw new Exception("Invalid Range!");
} else {
throw new InputMismatchException("Invalid Format!");
}
} catch (Exception ex) {
System.out.println(ex.getMessage());
scr.next();
}
}
scr.close();
return numInt;
}
This is the output I'm trying to get:
If you enter anything other than an int the error will get thrown at the line:
numInt = scr.nextInt();
And then get caught in the catch block, thus skipping the print statement. You need to check if there is a next int:
if(!scr.hasNextInt()) {
throw new InputMismatchException("Invalid Format!");
}
Also, how can I close the Scanner in a finally clause without causing an infinite loop.
You do not need to close the Scanner in a finally block. In fact, you shouldn't close it at all. It is bad practice to close System.in. Generally if you did not open a resource, you should not close it.
You need to catch InputMismatchException in a separate catch block before Exception catch block and add scr.next(); like following:
public static int getValidatedInteger(int i, int j) {
Scanner scr = new Scanner(System.in);
int numInt = 0;
while (numInt < i || numInt > j) {
try {
System.out.print("Please input an integer between 4 and 19 inclusive: ");
numInt = scr.nextInt();
if (numInt < i || numInt > j) {
throw new Exception("Invalid Range!");
}
} catch (InputMismatchException ex) {
System.out.println("Invalid Format!");
scr.next();
} catch (Exception ex) {
System.out.println(ex.getMessage());
scr.next();
}
}
scr.close();
return numInt;
}
Below code will work for you,this is the another approach you can use to get your desire output.
In this code i have handled the InputMismatch in catch block.
public static int getValidatedInteger(int i, int j) {
Scanner scr = new Scanner(System.in);
int numInt = 0;
while (numInt < i || numInt > j) {
try {
System.out.print("Please input an integer between 4 and 19 inclusive: ");
numInt = scr.nextInt();
if (numInt < i || numInt > j) {
System.out.println("Incorrect Range!");
}
} catch (InputMismatchException ex) {
System.out.println("Incorrect format!");
scr.next();
}
}
scr.close();
return numInt;
}

Whats wrong with my code? Do while and Try Catch

Keep getting syntax error, insert while expression to complete do statement. It maybe something simple like curly brackets etc.
{
int num = 0;
//flag
boolean inputOk = false;
Scanner s = new Scanner (System.in);
do {
try {
System.out.println("Enter a number....");
num =s.nextInt();
System.out.println("you entered : " + num);
// got here then things are good
inputOk = true;
} catch (InputMismatchException ex) {
System.out.println("Again please....digits only");
// flush the scanner
s.next();
}
} while (inputOk != true);
s.close();
System.out.println("Thank you");
}
In your code you are missing ending curly brackets "}" for do. For Scanner it's better to use try with resource. here is working code
int num = 0;
//flag
boolean inputOk = false;
try (Scanner s = new Scanner(System.in)) {
do {
try {
System.out.println("Enter a number....");
num = s.nextInt();
System.out.println("you entered : " + num);
// got here then things are good
inputOk = true;
} catch (InputMismatchException ex) {
System.out.println("Again please....digits only");
// flush the scanner
s.next();
}
}
while (inputOk != true);
}
System.out.println("Thank you");
You are missing ending curly brackets "{" of Do I have corrected it in below code
int num = 0;
//flag
boolean inputOk = false;
Scanner s = new Scanner (System.in);
do {
try {
System.out.println("Enter a number....");
num =s.nextInt();
System.out.println("you entered : " + num);
// got here then things are good
inputOk = true;
} catch (InputMismatchException ex) {
System.out.println("Again please....digits only");
// flush the scanner
s.next();
}} while (inputOk != true);
{
s.close();
System.out.println("Thank you");
}

Try - Catch in if - else if instruction

I was able to implement the function of the try - catch for the variable choice and it works great. I have a problem with variable stopnie. I want to check if this is numerical value. I tried to throw it in the try catch, unfortunately without success
class Task {
public static void main(String[] args) {
Scanner user_input = new Scanner (System.in);
System.out.println("Pick 1 to convert Fahrenheit to Celsius");
System.out.println("Pick 2 to convert Ceslius to Fahrenheit");
int choice = 0;
double stopnie = 0.0;
double convert = 0.0;
DecimalFormat df = new DecimalFormat("0.00", new DecimalFormatSymbols(Locale.US));
boolean loop = true;
while (loop)
{
try
{
choice = user_input.nextInt();
loop = false;
}
catch (Exception e)
{
System.out.println("Bad value");
System.out.println("Try again");
user_input.next();
}
}
if(choice == 1)
{
System.out.println("Let me know Celsius value");
stopnie = user_input.nextDouble();
convert = stopnie/1.8-35;
System.out.println(stopnie + " C " + " = " + df.format(convert) + " F");
}
else if (choice == 2)
{
System.out.println("Let me know Fahrenheit value");
stopnie = user_input.nextDouble();
convert = stopnie*1.8+35;
System.out.println(stopnie + " F " + " = " + convert + " C");
}
else
{
System.out.println("Bad value");
}
}
}
so, I added try catch to if(choice == 1): with while loop
if(choice == 1)
{
while (loop)
{
try {
System.out.println("Let me know Celsius value");
stopnie = user_input.nextDouble();
convert = stopnie/1.8-35;
System.out.println(stopnie + " C " + " = " + df.format(convert) + " F");
} catch (Exception e) {
System.out.println("Bad value");
System.out.println("Try again");
user_input.next();
}
}
}
Now, when I start program and Pick 1 nothing happens. I want to pick 1, go to function if(chooice ==1) and if there will be any error print Bad value, try again and add input to put value again
try this code:
public static void main(String[] args) {
Scanner user_input = new Scanner (System.in);
try {
int f=user_input.nextInt();
System.out.println("It's an Integer");
} catch (InputMismatchException e) {
System.out.println("It's not Integer");
// Should print the exception
//e.printStackTrace();
}
}

Categories

Resources