I want to enter numbers between 0 to 20 and that a message says saying nros outside the interval if it is not fulfilled but using exceptions

0
package excepciones;

import java.util.InputMismatchException;
import java.util.Scanner;

public class excepcion2 {
      static void rango(int num)throws calcular
      {
            if((num>20)||(num<0)){
                throw new calcular("Números fuera del intervalo");
            }
      }  
    public static void main(String[] args) throws calcular
    {
        Scanner entrada= new Scanner(System.in);
        int n;

        try {
        System.out.println("Ingrese un nro entre 0 y 20");
        n=entrada.nextInt();
        rango(n);
            }
        catch(InputMismatchException e)
        {
            System.out.println("Ingrese caracteres numericos");
        } 
    }
    public class calcular extends Exception
    {   
    public calcular()
    {}
    public calcular(String msj_error)
    {
        super(msj_error);
    }
    }

}
    
asked by Elenasys 20.09.2017 в 22:45
source

1 answer

0

First, it did not work because you have an internal class which is a class to make an exception and you try to call it from a static method. then you have to change that and the call from the main method to not be a static method of the class you have to create an instance of the class. By the way, the names of classes and methods must be self-documented, yours give rise to errors since the class that stands for exception is called calculate and does not calculate anything is an exception then the main class is called exception2, it is not a class that extends of exception ..... incomprehensible hahaha here the solution aaa and also captures an exception MIstMatchException or something like that hahaha that will never be released, that is to say, you also throw the exception that you create in the main method and at the same time also capture with a method try-catch that's a serious error, plus the main method should never throw the exceptions:

public class EvidenceExceptions {

  public void validarRango(int num)throws ExcepcionRango
  {
        if((num>20)||(num<0)){

            throw new ExcepcionRango("No esta en el intervalo");
        }else {
            System.out.println("Esta comprendido en el intervalo");
        }
  } 
  public class ExcepcionRango extends Exception
  {   


      public ExcepcionRango(String msj_error)
      {
          super(msj_error);
      }
    }
  public static void main(String[] args)
  {
    Scanner entrada= new Scanner(System.in);
    int n;


    System.out.println("Ingrese un nro entre 0 y 20");
    n=entrada.nextInt();
    try {
        PruebadeExcepciones objetoClase=new PruebadeExcepciones();
        objetoClase.validarRango(n);
    } catch (ExcepcionRango e) {
        System.out.println(e);
    }

  }

}

    
answered by 20.09.2017 в 23:18