循环在Java结束后,对字符串的更改仍然有效

时间:2014-03-11 09:52:45

标签: java string loops for-loop while-loop

所以我有这个脚本:

class input {
public static void main (String[] args){
    String hexa;
    hexa = "68101005200B10034D201A10162014100D17060520100F06200E101306200409020D0D060F0806200A0F201A101613200B1016130F061A4F2075090A1420100F06201802142007020A130D1A200602141A20151020041302040C4F207802140F4815200A156020525359200C061A14200A1420022012160A150620140E020D0D200C061A14110204064D201410200A1520140910160D050F481520090217062015020C060F201A101620151010200D100F0820151020050604131A11152015090A14200E0614140208064F2078060D0D2005100F064D201A1016132014100D16150A100F200A14200F050311030210130A0D10074F";
    int pituus;
    pituus = hexa.length();
    int i = 1;
    char luku;
    char luku2;
    int asc;
    String pari;
    String koodi;
    StringBuilder sb2 = new StringBuilder();
    StringBuilder sb = new StringBuilder();
    StringBuilder ASCII = new StringBuilder();
    for(int a = 0;a <30;a++){
    if (a > 0){
        hexa = sb.toString();
    }while(i < pituus){
    luku = hexa.charAt(i);
    luku2 = hexa.charAt (i-1);
    luku++;
           if(luku == 'G'){ 
        luku = '0';
        luku2++;
    }
           else if(luku == ':')
               luku = 'A';

    if (luku2 == '8')
        luku2 = '0';
 sb2.append(luku2);
 sb2.append(luku);
 pari = sb2.toString();
 sb2.setLength(0);
 asc = Integer.parseInt(pari,16);
 ASCII.append((char)asc);
 sb.append(luku2);
 sb.append(luku);
 i+=2;
    }
    koodi = ASCII.toString();
    System.out.printf("All hex pair values increased by: %d\n%s\n======================\n%s\n",a+1,hexa,koodi);
    }
}
}

EDIT2:现在在这个版本上,hexa就在程序步骤之前,到了while循环。在while循环中,程序使用hexa的旧值。为什么这样以及如何“更新”while循环?

3 个答案:

答案 0 :(得分:2)

手动或在调试器中逐步执行程序。您会发现pituus首先设置为0并且永远不会更改,因此永远不会输入内部while - 循环。

答案 1 :(得分:1)

我认为内部循环永远不会被执行。

因为最初pituus0并且内部循环未执行且sb.toString();""pituus再次为0,因此,内部循环永远不会被执行。

答案 2 :(得分:0)

我刚刚运行了你的代码(JDK 1.7.0_21),并且在main方法结束时确实改变了hexa变量的值:

hexa = "69111106210C11044E211B11172115110E18070621111007210F11140721050A030E0E07100907210B10211B111714210C11171410071B5021760A0B1521111007211903152108030B140E1B210703151B21161121051403050D5021790315104916210B16612153545A210D071B15210B1521032113170B160721150F030E0E210D071B15120305074E211511210B1621150A11170E06104916210A0318072116030D0710211B111721161111210E11100921161121060705141B121621160A0B15210F071515030907502179070E0E21061110074E211B1117142115110E17160B1110210B152110060412040311140B0E110850"

请尝试自行运行代码并提供预期和实际结果的详细报告。

P.S。 为了能够在main方法的末尾看到hexa的值,考虑在那里调用非修改方法:

            [...]
            koodi = ASCII.toString();
            System.out.print(koodi);
        }
        hexa.hashCode(); // place breakpoint here to see that the value has changed
    }
}