【问题标题】:Why I can't printout value from main method? [duplicate]为什么我不能从 main 方法打印值? [复制]
【发布时间】:2020-08-26 00:25:33
【问题描述】:

//我现在想知道为什么我不能在下面的java代码中打印出返回值

public class client08 {
public static void main(String[] args) {
    
    String w=test();
    System.out.println(w);**// I'd like to print out the return value here but it now work**
}
public String test() {
    String result="";
    String[] words=new String[5];
    words[0]="Amy";
    words[2]="Tom";
    words[4]="Jane";
    
    for(int i=0; i<words.length;i++) {
        if(words[i]!=null) {
            result=words[i].toUpperCase();  
        }else {
            result="null";
            }
    }
    return result;
    
}

【问题讨论】:

  • 您必须更具体地了解问题。它是关于从静态上下文调用非静态方法的吗?

标签: java return


【解决方案1】:

首先,类名应以大写字符开头。学习并遵循 Java 约定。

下一步:

  1. 您的代码无法编译。

  2. 您不能从“client08”类调用方法,除非您创建该类的实例或将方法设为静态。

所以代码应该是:

//String w=test();
client08 client = new client08();
String w= client.test();

或者您需要将方法设为静态:

public static String test() {

然后您将使用以下方法调用该方法:

String w = client08.test();
System.out.println(w);

【讨论】:

    猜你喜欢
    • 2019-02-20
    • 2016-05-06
    • 1970-01-01
    • 1970-01-01
    • 2020-06-17
    • 2013-01-05
    • 2012-02-25
    • 1970-01-01
    • 2013-07-11
    相关资源
    最近更新 更多