icenine icenine - 1 month ago 7
Java Question

Exceptions in Java - Try/ Catch

I'm learning Java and I have this program that tells the sign depending on the day and month the user writes. The program works as it is, but if the user enters a day like 90 or so, the program doesnt evaluate that "error". Can I correct this with a try/catch? If so, how do I write it? Here's the code (a piece of it), thanks in advance

import java.util.Scanner;
public class Signo{
public static void main(String[] args) {

Scanner in = new Scanner(System.in);

int day, month;


System.out.println("Day Input:");

day=in.nextInt();

System.out.println("Month Input:");

month=in.nextInt();

int result=getSign(day,month);

}

private static int getSign(int day, int month){

switch(month){
case 1:
if(month==1 && day>=20){
System.out.println("Your sign is Aquarius");
}else{
System.out.println("Your sign is Capricorn");
}
break;
//etc
}
return day;
}
}

Answer

It's pretty simple, really...

try
{
     //statements that may cause an exception
}
catch (exception(type) e(object))‏
{
     //error handling code
}

That's all you really need right there. Just put your code that you think might break in the appropriate spot.

Though, having read the comment, I agree that this is overkill for what you're doing.

You just need to set a condition for a While loop:

boolean goodAnswer = false;

while goodAnswer == false{
   System.out.println("Day Input:");
   day=in.nextInt();

  if (day<31) { goodAnswer=true; }
}

A routine like this will effectively keep on asking for an integer until it gets one it likes. Only then will it leave the loop. This is a fairly common approach for this sort of thing.

Comments