以十六进制读取文件并将其转换为十进制

时间:2014-10-22 14:49:10

标签: java java.util.scanner

当读取包含基数为16的数字的文件时,我的扫描仪只读取偶数,在奇数上抛出没有这样的元素异常......我是java的新手所以这可能很简单,但我不知所措。我目前的代码如下......

import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.NoSuchElementException;

public class HexToDecimalConverter {
    public static void main(String[] args) {
        try {
            Scanner HexFile = new Scanner(new File("Hexidecimal.txt"));

            do {
                String Hex = HexFile.next();
                System.out.println(Hex);
                int outputDecimal = Integer.parseInt(Hex, 16);
                System.out.println(outputDecimal);
            } while (HexFile.next() != "  ");

        } catch (FileNotFoundException fileNotFoundExc) {
            System.out.println("file not found");
            System.exit(0);
        } catch (IOException IOExc) {
            System.out.println("IO Exception");
            System.exit(0);
        } catch (NoSuchElementException noSuchElementExc){
            System.out.println("No Such Element");
            System.exit(0);
        }


    {
    }
}
}

2 个答案:

答案 0 :(得分:1)

你的情况:

} while (HexFile.next() != "  ");

还会读取十六进制数并将其丢弃(因为您不会将其返回值存储在任何位置)。这解释了为什么只有代码打印偶数。

而是使用以下条件:

} while (HexFile.hasNext());

Scanner.hasNext()只测试是否有更多令牌,但如果有更多令牌则不会读取或丢弃下一个令牌。

此外,您可能希望使用while循环,该循环在读取之前进行测试,因为该文件可能不包含任何内容,例如:

while (HexFile.hasNext()) {
    String Hex = HexFile.next();
    // rest of your code
}

答案 1 :(得分:0)

那是因为你两次打电话给HexFile.next()
首先更改代码如下:

    String Hex = HexFile.next();
    while (Hex!= "  ") {
        System.out.println(Hex);
        int outputDecimal = Integer.parseInt(Hex, 16);
        System.out.println(outputDecimal);
        String Hex = HexFile.next();
    } 
相关问题