2013-08-18 48 views
0

正如標題所示:我有一個需要調用的方法,但我不知道如何。這裏的方法:如何使用if else語句調用方法

public static int wordOrder(int order, String result1, String result2){ 
    order = result1.compareToIgnoreCase(result2); 
    if (order == 0){ 
     System.out.println("The words are the same."); 
    }else if (order > 0){ 
     System.out.println("The order of the words alphabetically is " +result2+ " then " +result1+ "."); 
    }else{ 
     System.out.println("The order of the words alphabetically is " +result1+ " then " +result2+ "."); 
    } 
    return order; 
    } 

我該如何在主要方法中調用?任何幫助將是偉大的!謝謝!

+0

沒有理由讓'int order'作爲方法的參數。 –

+1

請參閱Oracle Java教程中的[將信息傳遞給方法或構造函數](http://docs.oracle.com/javase/tutorial/java/javaOO/arguments.html)。 – Jesper

回答

1

它應該是這樣的

主要方法

public static void main(String[] args) { 
     int resultFromMethod= wordOrder(2,"result1","result2"); 
    // your method accept argument as int, String , String and 
    // it is returning int value 
    } 

這是你的方法

public static int wordOrder(int order, String result1, String result2){ 
     order = result1.compareToIgnoreCase(result2); 
     if (order == 0){ 
      System.out.println("The words are the same."); 
     }else if (order > 0){ 
      System.out.println("The order of the words alphabetically is " +result2+ " then " +result1+ "."); 
     }else{ 
      System.out.println("The order of the words alphabetically is " +result1+ " then " +result2+ "."); 
     } 
     return order; 
    } 

這活Demo可以幫助你。

2

像這樣:wordOrder(1, "a", "b");(雖然第一個參數沒有意義)。

+0

我將如何設置參數? – Salma

+2

只需*寫*他們就像在給定的例子。 – qqilihq

+1

@Salma跟你所說的其他方法一樣。 'System.out.println(String s)'是一種方法,你知道的。 – hexafraction

0

qqilihq給你正確的答案,但你可以從功能未使用的變量消除並讓功能:

public static int wordOrder(String result1, String result2){ 
    int order = result1.compareToIgnoreCase(result2); 
    if (order == 0){ 
    System.out.println("The words are the same."); 
    }else if (order > 0){ 
    System.out.println("The order of the words alphabetically is " +result2+ " then " +result1+ "."); 
    }else{ 
    System.out.println("The order of the words alphabetically is " +result1+ " then " +result2+ "."); 
    } 
    return order; 
} 

,並調用這個函數:

wordOrder("a","b"); 
+0

@AndrewMartin不,他沒有,他從方法簽名中刪除了「int order」。 –

+0

additionaly我從功能刪除了不必要的參數;) –

+0

公平不夠 - 道歉! –

1

如果我明白了,你只想要調用方法從主要方法。該代碼可以是這樣

public static void main(String [] args){ 
    int myOrder = wordOrder(1, "One word", "Second word"); 
} 

public static int wordOrder(int order, String result1, String result2){ 
    order = result1.compareToIgnoreCase(result2); 
    if (order == 0){ 
     System.out.println("The words are the same."); 
    }else if (order > 0){ 
     System.out.println("The order of the words alphabetically is " +result2+ " then " +result1+ "."); 
    }else{ 
     System.out.println("The order of the words alphabetically is " +result1+ " then " +result2+ "."); 
    } 
    return order; 
    } 

作爲一個額外注:如果方法wordOrder被設置爲靜態這隻能做,如果沒有它會出現一個它不能被引用非來自靜態上下文的靜態方法。