How do I return the values and variables from non main method to main method?

Zerenity :

Im trying to make this program work but im getting the error that it cant find the variable min and max in the system.out.print statement in main method. I guess it is because main doesnt know what those variables are since the MinMax destroys those variables once its ran. But how can I transfer the results over from my MinMax method so that results will be printed in system.out.print in main method statement?

class MethodMinMaxWithUnlimitedValues {

  public static void main(String[]args) {

    Scanner console = new Scanner (System.in);

    int value;
    char choice;

    do{
      System.out.print ( " enter value " );
      value = console.nextInt();

      isMinMax(value);

      System.out.print ("enter more numbers? (y/n) ");
      choice = console.next().charAt(0);
    }

    while (choice == 'y' || choice == 'Y');

    System.out.print("min value is = " + min + " max value is = " + max);
  }

  public static void isMinMax (int n) {

    int min = Integer.MIN_VALUE;
    int max = Integer.MAX_VALUE;

      if (n > max) {
        max = n;

      } else if (n < min) {
        min = n;
      }

    }
}
Rias :

Make them static and global

import java.util.Scanner;

class MethodMinMaxWithUnlimitedValues {

    static int min = Integer.MIN_VALUE;
    static int max = Integer.MAX_VALUE;


    public static void main(String[]args) {

        Scanner console = new Scanner (System.in);

        int value;
        char choice;

        do{
            System.out.print ( " enter value " );
            value = console.nextInt();

            isMinMax(value);

            System.out.print ("enter more numbers? (y/n) ");
            choice = console.next().charAt(0);
        }

        while (choice == 'y' || choice == 'Y');

        System.out.print("min value is = " + min + " max value is = " + max);
    }

    public static void isMinMax (int n) {

        if (n > max) {
            max = n;

        } else if (n < min) {
            min = n;
        }

    }
}

NOTE: that can have side effects

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=217316&siteId=1