我对Java完全不熟悉,我想知道为什么这个函数没有打印任何东西。
public class testingStuff {
public String func(){
int i;
String foo = "";
for (i=0; i<3; i++ ){
foo = "The number is "+i + " \n";
}
return foo;
}
public static void main(String[] args)
{
testingStuff stuff = new testingStuff();
stuff.func();
}
}
答案 0 :(得分:4)
public class testingStuff
{
public String func()
{
int i;
String foo = "";
for (i=0; i<3; i++ )
{
foo += "The number is "+i + " \n";
}
return foo;
}
public static void main(String[] args)
{
testingStuff stuff = new testingStuff();
String s = stuff.func();
System.out.println(s); //this will print to console.
}
}
或者如果您更喜欢这样:
public void func()
{
int i;
String foo = "";
for (i=0; i<3; i++ )
{
foo = "The number is " + i;
System.out.println(foo);
}
}
public static void main(String[] args)
{
testingStuff stuff = new testingStuff();
stuff.func();
}
答案 1 :(得分:2)
您没有使用System.out.println()
来打印值。
您所做的只是将一个句子分配给局部变量foo
,然后返回其最后一个值(不使用它)。
尝试:
for (i=0; i<3; i++ ){
System.out.println("The number is "+i + " \n");
}
答案 2 :(得分:0)
代码中的修改很少
public static void main(String[] args) {
testingStuff stuff = new testingStuff();
System.out.println(stuff.func()); // prints the result
}
答案 3 :(得分:0)
public class TestingStuff {
public void func(){
for (int i=0; i<3; i++ ){
System.out.println("The number is " + i);
}
}
public static void main(String[] args)
{
new testingStuff().func();
}
}