2015-09-18 93 views
-2

我只想知道如何在java中調用方法/函數。你能幫我解決這個問題嗎?在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); 
    } 
} 
+0

問題是? – Kamo

回答

0

您對MyFirstProject類使方法hello靜態,因此它具有內涵 - >Explanation

但這裏的問題是,你缺少的參數傳遞給方法:

int example_arg_one = 3; 
int example_arg_two = 5; 

MyFirstProject.hello(example_arg_one,example_arg_two); 
0

因爲你的方法hello(int a, int b)有兩個整數的參數,你需要給它的整數爲了調用它時爲它工作。但這也是沒有意義的,因爲你有一個掃描儀,它定義了你的方法中的整數。只要刪除你的方法的參數,你的代碼應該工作。

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); 
} 

關於如何調用方法,你做的是對的。只是不要忽視你的參數,如果你的方法有一個你必須給它一個。如果你不知道參數是什麼,那麼這就是你好(int a,int b)。你的方法期望你給它兩個整數,因爲這是你如何定義你的方法,你定義它需要兩個整數。如果你想使用該參數來調用它,把它在你的主,並給它兩個整數,例如hello(1, 2)

注:如果你想這樣做,你必須從刪除scan.nextInt()你碼。

0

您忘記將兩個參數a和b傳入方法hello。

public static void main(String[] args) { 

    int a = 1; 
    int b = 2; 

    hello(a,b); 
} 
+0

非常感謝。 –