仅在没有迭代的情况下打印总值一次

时间:2015-09-24 15:48:21

标签: java

我想打印语句System.out.println(sb.append(ss));

只是我最后一次尝试将其从for循环中取出但结果是错误的。

 public static String constatmentvertBinaryStringToString(String string) {
    StringBuilder sb = new StringBuilder();
    char[] chars = string.toCharArray();
    String ss = null;

    //for each character
    for (int j = 0; j < chars.length; j += 8) {
        int idx = 0;
        int sum = 0;
        //for each bit in reverse
        for (int i = 7; i >= 0; i--) {
            if (chars[i + j] == '1') {
                sum += 1 << idx;
            }
            idx++;
        }
        System.out.println(sum); //debug
        int div = sum / 4;
        System.out.println(div);
        System.out.println((char) div);
        int rem = sum % 4;
        System.out.println(rem);
        ss = (char) div + "" + rem;
        System.out.println(sb.append(ss));
    }
    return sb.toString();
}

2 个答案:

答案 0 :(得分:0)

放入System.out.println(sb.append(ss));走出循环:

public static String constatment vertBinaryStringToString(String string){
   StringBuilder sb = new StringBuilder();
   char[] chars = string.toCharArray();
   String ss=null;
   //for each character
   for (int j = 0; j < chars.length; j+=8) {
      int idx = 0;
      int sum =0;
      //for each bit in reverse
      for (int i = 7; i>= 0; i--) {
         if (chars[i+j] == '1') {
            sum += 1 << idx;
      }
      idx++;
   }            
   System.out.println(sum); //debug
   int div=sum/4;
   System.out.println(div);
   System.out.println((char)div);
   int rem=sum%4;
   System.out.println(rem);
   ss=(char)div+""+rem;   
   } 
   System.out.println(sb.append(ss));
   return sb.toString();
}

答案 1 :(得分:0)

由于'<%# ((GridViewRow)Container).FindControl("textDateSent").ClientID %>' 包含对System.out.println(sb.append(ss));的调用,因此从sb.append(ss));循环中取出该语句的结果将与预期结果不同。

您应该将for保留在循环中,并在循环外添加sb.append(ss);

System.out.println(sb)