0

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

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

4 回答 4

2

像这样:(wordOrder(1, "a", "b");虽然第一个参数没有意义)。

于 2013-08-18T15:21:24.363 回答
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;
    }

这个现场演示可能会对您有所帮助。

于 2013-08-18T15:23:55.320 回答
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设置为静态时才能这样做,如果没有,它会显示它不能从静态上下文中引用非静态方法。

于 2013-08-18T15:33:28.643 回答
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");
于 2013-08-18T15:26:53.990 回答