如何使用if else语句调用方法

时间:2013-08-18 15:20:27

标签: java methods

正如标题所说:我有一个我需要调用的方法,但我不确定如何。这是方法:

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

我应该如何在main方法中调用它?任何帮助都会很棒!谢谢!

4 个答案:

答案 0 :(得分:2)

像这样:wordOrder(1, "a", "b");(第一个参数毫无意义)。

答案 1 :(得分: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 :(得分:1)

如果我理解,你只想从main方法调用一个方法。代码可能是这样的

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设置为静态时才能执行此操作,否则会显示无法引用非来自静态上下文的静态方法。

答案 3 :(得分: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");