java无法为方法实践解决方法错误
public class MainForm {
String varpass = "This is a string that has to be passed.";
public String t1(){
String text = "This is a non-static method being called.";
return text;
}
public static String t2(){
String text = "This is a static method being called.";
return text;
}
public void t3(){
System.out.println("This is a non-static void method and cannot return.");
}
public static void t4(){
System.out.println("This is a static void method and cannot return.");
}
public void place1 (){
//=======================================Method calls from another class========================================
//Calls from another class. It is non-static and thus requires it to be instantiated. EG. class var = new class();
Methods call = new Methods();
System.out.println(call.t1());
//Calls from another class. It is non-static void and thus requires it to be instantiated and be called straight.
call.t3();
//Calls from another class. It is static and thus does not require it to be instantiated. EG. class var = new class();
System.out.println(Methods.t2());
//Calls from another class. It is static void and thus does not require it to be instantiated.
Methods.t4();
//Trying to call a variable that was sent.
Methods.getvar(varpass);
call.getvar(varpass);
//=======================================Method calls from current class========================================
MainForm mcall = new MainForm();
//Calls from within the same class. It is static and thus does not require it to be instantiated. EG. class var = new class();
System.out.println(mcall.t1());
mcall.t3();
System.out.println(t2());
t4();
}
public static void main(String[] args) {
MainForm place = new MainForm();
place.place1();
}
}
public class Methods {
String var1 = "This is a public String variable";
String getVar = "Initial";
public String t1(){
String text = "This is a non-static method being called.";
return text;
}
public static String t2(){
String text = "This is a static method being called.";
return text;
}
public void t3(){
System.out.println("This is a non-static void method and cannot return.");
}
public static void t4(){
System.out.println("This is a static void method and cannot return.");
}
public void getvar(String varsent){
String msg = "getver() Variables are varsent("+varsent+"), getVar("+getVar+"), getVar(";
getVar = varsent;
msg = msg + getVar+")";
System.out.println(msg);
}
}
以下是错误
Methods.getvar(varpass);
call.getvar(varpass);
最重要的一点是,非静态不能从静态上下文引用
最下面的一个是无法解析方法“println(void)”
你可以告诉我,我是在练习调用方法
这里我试图传递一个包含字符串的变量varpass。我希望它在方法中将该变量传递给getvar。在这种情况下,getvar会在方法中获取一个变量,并在修改之前显示它,然后在修改之后再次显示它
我想知道这是怎么回事。如有任何见解,将不胜感激
# 1 楼答案
不能从静态方法中引用非静态变量/字段,因为类的实例之间的非静态字段可能会有所不同。要解决这个问题,让varpass
static
:第二个错误来自getvar的定义:
由于它不返回任何内容,因此不能在
System.out.println()
中使用,因为println
没有接受void的定义(它不知道打印什么)另外,
Methods.getvar(varpass)
应该是Methods.getvar(MainForm.varpass)
,因为没有具有该名称的局部变量