日期:2014-05-19  浏览次数:20728 次

循环问题?急
怎么把数组String []str={"aa","bb","cc","dd","ee","gg","ff","ll","kk","ii"};打印成
  aa bb cc
  dd ee gg
  ff ll kk
  ii
 这样写报越界异常
 for(int i=0;i<=str.length;)
{
for(int j=0;j<3;j++,i++)
{
System.out.print(str[i]);
}
System.out.println();
 
}
  大虾门指点啊!

------解决方案--------------------
for(int i=0;i<str.length;)
 {
 for(int j=0;j<3 && i<str.length;j++,i++)
 {
 System.out.print(str[i]);
 }
 System.out.println();
 
}
 
------解决方案--------------------
String []str={"aa","bb","cc","dd","ee","gg","ff","ll","kk","ii"};
for(int i=0;i<str.length;)
{
for(int j=0;j<3;j++,i++)
{
System.out.print(str[i] + " ");
}
System.out.println();

}
------解决方案--------------------
为什么要用双重循环?

Java code


public class Test {

    /**
     * @param args
     */
    public static void main(String[] args) {
        String []str={"aa","bb","cc","dd","ee","gg","ff","ll","kk","ii"};
        for(int i = 0; i < str.length; i++){
            if(i > 0 && i % 3 == 0){
                System.out.println();
            }
            System.out.print(str[i] + " ");
        }

    }

}

------解决方案--------------------
Java code

class TestContinue{
    public static void main(String args[]){
        String []str={"aa","bb","cc","dd","ee","gg","ff","ll","kk","ii"};
        int i = 0;
        for(String n: str){
            System.out.print(n + " ");
            i++;
            if(i%3 == 0){
                System.out.println();
                continue;
            }
        }
    }
}

------解决方案--------------------
我傻了,干嘛用那个continue....
------解决方案--------------------
Java code

class TestContinue{
    public static void main(String args[]){
        String []str={"aa","bb","cc","dd","ee","gg","ff","ll","kk","ii"};
        int i = 0;
        for(String n: str)
            System.out.print(n + ((++i)%3==0?"\n":"\t"));
    }
}

------解决方案--------------------
楼上方法 精简之上
------解决方案--------------------
Java code

String[] str={"aa","bb","cc","dd","ee","gg","ff","ll","kk","ii"};
        for(int i=0;i<str.length;i++){
            if(i!=0){
                if(i%3==0){
                    System.out.println();
                }else{
                    System.out.print(" ");
                }
            }
            
            System.out.print(str[i]);
        }

------解决方案--------------------