在没有传递值的情况下用Java调用方法的优雅方法是什么?

时间:2017-09-17 22:29:45

标签: java

希望能够在不传递值Summ(0,0)的情况下调用方法Summ。

如何以优雅的方式实现这一目标?

import java.util.Scanner;

    public class Recursive {

        public static void main(String[] args) {
           Summ(0, 0);

            }


       public static int Summ (int a ,int b) {

           System.out.println("Enter the first interger");
           Scanner sc = new Scanner(System.in);
           a = sc.nextInt();
           System.out.println("Enter the second interger");
           b = sc.nextInt();
           if (a < 0 || b<  0)
              return 0;
           else {
              int c = a+b;
              return c;
           }

2 个答案:

答案 0 :(得分:1)

参数对于方法是可选的。因此,在这种情况下,删除参数a和b,并将它们定义为Summ方法中的局部变量。以下是修改后的代码的外观。

import java.util.Scanner;

public class Recursive {

  public static void main(String[] args) {
    Summ();

  }

  public static int Summ() {

    System.out.println("Enter the first interger");
    Scanner sc = new Scanner(System.in);
    int a = sc.nextInt();
    System.out.println("Enter the second interger");
    int b = sc.nextInt();
    if (a < 0 || b < 0)
      return 0;
    else {
      int c = a + b;
      return c;
    }
  }
}

答案 1 :(得分:0)

更改为public static int Summ (){...},并将其称为:summ();也在函数内声明int a,b;

import java.util.Scanner;

public class Recursive {

    public static void main(String[] args) {
       Summ();

        }


   public static int Summ () {
     int a,b;

       System.out.println("Enter the first interger");
       Scanner sc = new Scanner(System.in);
       a = sc.nextInt();
       System.out.println("Enter the second interger");
       b = sc.nextInt();
       if (a < 0 || b<  0)
          return 0;
       else {
          int c = a+b;
          return c;
       }