Java - 跳过循环

时间:2014-02-02 01:44:13

标签: java for-loop

import java.lang.Integer;
import java.util.Arrays;

public class Decimal {

    //initialize intance variables
    private int decimal;
    private String hex;

    public static void toHex(String s) {
        int decimal = Integer.parseInt(s); //converts the s string into an int for binary conversion. 
        String hex = null;
        int[] binNum = new int[16];
        int[] binNumNibble = new int[4]; //A nibble is four bits.
        int nibbleTot = 0;
        char hexDig = '\0';
        char[] cvtdHex = new char[4];
        StringBuffer result = new StringBuffer();

        for(int a = 32768; a == 1; a /= 2) { //32768 is the value of the largest bit.
            int b = 0;//Will top at 15 at the end of the for loop. 15 references the last  spot in the binNum array. 
            if(decimal > a) {
                decimal -= a;
                binNum[b++] = 1;//Arrays have a default value of zero to all elements.     This provides a parsed binary number.
            }
        }

        for(int a = 0; a == 15; a += 3) {
            //Copies pieces of the binary number to the binNumNibble array. .arraycopy is used in java 1.5 and lower.
            //Arrays.copyOfRange is used in java 1.5 and higher.
            System.arraycopy(binNum, a, binNumNibble, 0, 4);

            for(int b = 8; b == 1; a += 3) {
                int c = 0;
                nibbleTot += binNumNibble[c++];

                //Converts the single hex value into a hex digit.
                if(nibbleTot >= 1 && nibbleTot <= 9) {
                    hexDig += nibbleTot;
                } else if(nibbleTot == 10) {
                    hexDig = 'A';
                } else if(nibbleTot == 11) {
                    hexDig = 'B';
                } else if(nibbleTot == 12) {
                    hexDig = 'C';
                } else if(nibbleTot == 13) {
                    hexDig = 'D';
                } else if(nibbleTot == 14) {
                    hexDig = 'E';
                } else if(nibbleTot == 15) {
                    hexDig = 'F';
                }

                cvtdHex[c++] = hexDig;
            }
        }
        //return hex = new String(cvtdHex);
        hex = new String(cvtdHex);
        System.out.print("Hex: " + hex);
    }
}

我似乎无法弄清楚为什么变量hex作为空白变量返回。我一直在使用System.out.print();在每个for循环中并没有使用它们,给我的印象是for循环被完全跳过,但我不明白为什么,我有时间限制。

非常感谢任何帮助,但请不要粘贴代码。我需要为我的计算机科学课理解这一点!

3 个答案:

答案 0 :(得分:4)

是的,你的for循环被跳过,因为for语句的第二部分不是中断条件,而是必须为循环运行填充的条件。

所以它不是

for(a = 0; a == 15; a += 3)

但是

for(a = 0; a <= 15; a += 3)

依旧......

答案 1 :(得分:1)

for loops由于双==

而无法执行

答案 2 :(得分:1)

怎么样

String.format("%h", 256)