public class program1{
String[] num = {"1","2","3","4"};
public String toString(){
String a = " this is ";
for(String test:num){
a += " " + test.toString(); //为什么这里不是" this is 1 this is 2 this is 3 this is 4 "这样的输出?
}
return a;
} public static void main(String[] args){
program1 mytest = new program1();
System.out.println(mytest.toString());
}
}这段代码的输出是 this is 1 2 3 4
String[] num = {"1","2","3","4"};
public String toString(){
String a = " this is ";
for(String test:num){
a += " " + test.toString(); //为什么这里不是" this is 1 this is 2 this is 3 this is 4 "这样的输出?
}
return a;
} public static void main(String[] args){
program1 mytest = new program1();
System.out.println(mytest.toString());
}
}这段代码的输出是 this is 1 2 3 4
String b = "this is";
String a = "";
for(String test:num){
a = a + b + test.toString();
}
循环的时候
test = num[0] = "1"
test = num[1] = "2"
test = num[2] = "3"
test = num[3] = "4"
所以循环下来a = a + "1" + "2" + "3" + "4"
就是说
每次循环只是在原有的字符串上加了个数字
追后加完了一起输出而已
你把输出放到循环里就会发现
this is 1
this is 1 2
this is 1 2 3
this is 1 2 3 4
每次只是加了个数字而已要实现你说的那种要在循环里面定义 a
for(String test:num){
String a = " this is "; //这样每次循环都会初始化a 这样就不会出现重复了
a += " " + test.toString();
System.out.println(a);
}