我尝试学习JAVA语言。我写简单的程序,但它不起作用。有人可以给我建议如何解决问题。 我的节目:
class WriteOut {
private static int sumas;
public void sud(int sds) {
sumas = sds;
}
public static void main(String arg[]) {
WriteOut sum =new WriteOut();
sum.sud(5);
System.out.println("suma: "+sum);
}
}
输出我得到“suma:bandymas.WriteOut@70dea4e”;
我想得到答案“suma:5”
答案 0 :(得分:1)
System.out.println()调用toString()方法,它来自基本的Object类。 有两种方法可以修复此代码:
1)重写standart toString()方法:
class WriteOut {
private static int sumas;
@Override
public String toString(){
return String.valueOf(sumas); // returns a string with sumas value
}
public static void main(String arg[]) {
WriteOut sum =new WriteOut();
sum.sud(5);
System.out.println("suma: "+sum);
}
}
2)或者只需更改System.out.println()调用:
class WriteOut {
public static int sumas; // To allow System.out.println() to see this variable
public void sud(int sds) {
sumas = sds;
}
public static void main(String arg[]) {
WriteOut sum =new WriteOut();
sum.sud(5);
System.out.println("suma: "+sum.sumas);
}
}
答案 1 :(得分:0)
将System.out.println()
内的内容更改为:
System.out.println(“suma:”+ sum.sumas);
示例:
class WriteOut {
private static int sumas;
public void sud(int sds) {
sumas = sds;
}
public static void main(String arg[]) {
WriteOut sum =new WriteOut ();
sum.sud(5);
System.out.println("suma: "+sum.sumas);
}
}
输出:
suma: 5