在java中调用简单方法

时间:2015-09-18 08:09:59

标签: java java.util.scanner

我只想知道如何在java中调用方法/函数。你能帮帮我吗?

所以这是我的代码。

import java.util.Scanner;

public class MyFirstProject {

    public static void main(String[] args) {

        hello();
    }

    static void hello(int a, int b) {
        Scanner scan = new Scanner(System.in);
        int total;
        System.out.print("Enter first number: ");
        a = scan.nextInt();
        System.out.print("Enter second number: ");
        b = scan.nextInt();

        total = a + b;

        System.out.println("The total is: " + total);
    }
}

3 个答案:

答案 0 :(得分:0)

点击2次,这是一个图示的答案 - http://www.wikihow.com/Call-a-Method-in-Java

在您的代码中,您实际缺少的是传递所需的参数 - ab的值。该调用实际上应该看起来像MyFirstProject.hello(2, 5)

答案 1 :(得分:0)

由于您的方法hello(int a, int b)具有两个整数的参数,因此在调用它时需要给它整数以使其起作用。但这也没有意义,因为你有一个Scanner在你的方法中定义你的整数。只需删除方法的参数,您的代码就可以正常工作。

    public static void main(String[] args) {

    hello();
}

static void hello() {
    Scanner scan = new Scanner(System.in);
    int total;
    System.out.print("Enter first number: ");
    int a = scan.nextInt();
    System.out.print("Enter second number: ");
    int b = scan.nextInt();

    total = a + b;


    System.out.println("The total is: " + total);
}

关于如何调用方法,你做得对。只是不要忽略你的参数,如果你的方法有一个你必须给它一个。如果您不知道参数是什么,则为hello (int a,int b)。你的方法期望你给它两个整数,因为这是你定义你的方法的方法,你定义它采取两个整数。如果你想使用参数调用它,请在main中调用它并给它两个整数,例如hello(1, 2)

注意:如果你想这样做,你必须从你的代码中删除scan.nextInt()。

答案 2 :(得分:0)

您忘了将两个参数a和b传递给方法hello。

public static void main(String[] args) {

    int a = 1;
    int b = 2;

    hello(a,b);
}