javamethodsinputmismatchexception

Is there a way to only get the value from an input method to another method without repeating the whole process again in java?


I really want to know if there is a way to only get the value from the method to an another method. Because in the main method the first method is already call out while the the second needed the value of the input from the first method.

//Main method public static void main(String[] args) {

Scanner reader = new Scanner(System.in);

  int an = 0;

  an = first_method(an);

  second_method();

}

//First Method

static int first_Method (int num) {

    Scanner reader = new Scanner(System.in);

    boolean done = false;

    int num = 0;

    while(!done) { 
                                                
        try {

            System.out.print("Enter a Number: \t\t");

            num = reader.nextInt();

            done = true;

           }

        catch (InputMismatchException e) {

            String s = reader.nextLine();

            System.out.println("Invalid a number: " + s);

           }

    }

    return num;

}

//Second Method

static void second_method() {

  int anum = 0;

  anum = first_method(anum);

  System.out.println(anum);

}

P.S. I know that my question have similar question from others in here but so far from what I have search there is none that solve my problem with a mismatch exception so if there is any same problem as me and already question in here then you can link it. Thanks


Solution

  • Sure. Its called a 'parameter':

    static void secondMethod(int v) {
        System.out.println(v);
    }
    
    public static void main(String[] args) {
      Scanner reader = new Scanner(System.in);
      int an = firstMethod(an);
      secondMethod(an);
    }
    

    Here, you let firstMethod run, it produces a result (it's what you return). You then pass that result to secondMethod. Parameters are like local variables, except they are initialized to a value that the code that invokes your method determines. Here, the secondMethod method has a local variable named v, and its value starts out as whatever the code that calls secondMethod wants it to be. Here, we want it to be whatever firstMethod returned, thus letting us pass something firstMethod calculated, to secondMethod to work on.