-1

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;
    }
    }
icenine
  • 23
  • 7
  • what error? you asked for an integer, user provided an integer. It's up to YOU to write the code to say "that integer is too big". and no, a try/catch isn't suitable for that. – Marc B Oct 18 '16 at 20:04
  • What is the purpose of the switch if you use an if statement anyways? – OneCricketeer Oct 18 '16 at 20:06
  • You might find this useful to get the max days in a month. http://stackoverflow.com/a/1806433/2308683 – OneCricketeer Oct 18 '16 at 20:08

4 Answers4

1

There is actually no error. You are asking for an integer and the user is providing just that. It is up to you to verify if it is a valid number for your current logic. I would also re-write your getSign() method, there is really no point in mixing a switch and an if. Not at least in your case.

I would do something like this:

day=in.nextInt();
if(day > 30) {
    while(day > 30) {
        // Number is too high, feel free to spit this message out
        day=in.nextInt();
    }

Or even better:

while(day > 30) {
    day=in.nextInt();
}

You could also extract your day = in.nextInt(); to a single method and return a boolean if it is valid/invalid

facundop
  • 482
  • 6
  • 28
  • That should be day > 31, to allow for months like January (and October). – Penguino Oct 18 '16 at 20:21
  • It is just an example - the proper way to do it would be to verify each month (and year) for a valid date. The idea tho is the same. – facundop Oct 18 '16 at 20:24
0

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.

durbnpoisn
  • 4,666
  • 2
  • 16
  • 30
0

You would be looking for something of an assertion/validation, which is usually done on a method's arguments:

public void doSomething(int num) {
    if (num > 30) {
        throw new IllegalArgumentException("num is too high!");
    }
    //continue knowing that num is <= 30
}

There are APIs (like Apache Commons) which simplify this to one line:

Validate.isTrue(num <= 30, "num is too high!");

Which does the same code in essence as above, but much shorter.

All of this is a part of Data Validation

For doing a logical loop on this:

boolean valid = false;
while (!valid) {
    try {
        //take input, pass to #doSomething
        valid = true;
    } catch (IllegalArgumentException ex) {
        //repeat / error out
    }
}
//continue

Though you may wish to just manually validate yourself with something like an isValid check:

private boolean isValidDay(int num) {
    return num > 0 && num < 31;
}

//In method
Validate.isTrue(isValidDay(num), "num is not valid!");

//Without try/catch
if (isValidDay(num)) {
    //call #doSomething etc
}
Rogue
  • 11,105
  • 5
  • 45
  • 71
0

You should not be using the try/catch at all.

There are two types of Exceptions in Java - Caught/Checked Exceptions and Uncaught/Unchecked Exceptions (RuntimeException, Error, and their subclasses). The Exception in your case is an example of an Uncaught/Unchecked Exception as this happens during runtime due to user input.

You do not need try/catch blocks for these exceptions for the most part. In fact, you do not even need to handle these exceptions. So what do you do?

You improve your logic in the code so that the exception does occur. For example, you can use a while loop to keep asking the user for a valid number.

if(day > 30) {
    While(day > 30) {
        //send message to the user 
        day = in.nextInt();    
    }
}
Sameer Khanal
  • 1,199
  • 12
  • 11
  • Ok, thanks for that explanation. The loop is very logical, i guess i'll use the try/catch some other time :) – icenine Oct 18 '16 at 20:56