Java中的List <string>出错

时间:2017-09-12 23:52:50

标签: java string list

我有一个程序来创建一个String来构建一个表,它可以正常工作,直到我需要&#34;离开循环&#34; (当allClear应该为true时)但它会一直返回false。

我尝试打印String ret,它总是有一个类似于&#34; | | &#34 ;.由于这种情况发生,这意味着List l将所有字符串设置为&#34;&#34;,在这种情况下,allClear方法应该返回true。

这是为表构建列的方法的代码,它获取包含所有字符串的List以及表应该有多少列,然后返回包含所有表字符串的String。

它应该返回一个字符串,如:&#34; Col 1 | Col 2 | Col 3 \ nCol 1 | Col 2 |第3栏&#34;,

public static String buildNCol(List<String> l, int n)throws NotEnoughStringsException{
    if(l.size()<n)throw new NotEnoughStringsException("Not enough Strings given");
    int colSize = colSize(n);
    int colN,curChar,curSize;
    String ret="",temp="";
    boolean check = true;
    while(check){
        ret="";
        for(colN=0;colN<n;colN++){
            temp = getLine(l,colN,colSize);
            for(curSize=temp.length();curSize<colSize;curSize++)temp+=' ';
            if(colN!=n-1)temp+=" | ";
            ret+=temp;
        }
        ret+='\n';
        for(colN=0;colN<n;colN++)l.set(colN,cutString(l.get(colN)));
        if(allClear(l,n))check=true; //This is where the error happens
    }
    return ret;
}

这是allClear方法。此方法检查列表中的所有n个第一个字符串是否都设置为&#34;&#34;,null或&#34; \ n&#34;。

private static boolean allClear(List<String> l,int n){
    int i;
    String temp;
    for(i=0;i<n;i++){
        temp = l.get(i);
        if(temp!=null&&temp.length()>1) return false;
        if(temp.length()==1&&temp.charAt(0)!='\n')return false;
    }
    return true;
}

2 个答案:

答案 0 :(得分:1)

凯文安德森在评论中说,

check最初设置为true,当allClear返回true时有条件地设置为true。 while循环中的任何内容都没有将check设置为false或发出中断,因此它将永远循环。

您可以通过将check设置为false来解决此问题:

check = false;

答案 1 :(得分:0)

正如@KevinAnderson在评论中所说,程序中的错误是检查永远不会变错,因为我将其编码为&#34;更改&#34;为真而不是假