日期:2014-05-20  浏览次数:20906 次

初学java,有个问题请教:
import java.io.*;

//读取含十六进制码的文本文件
class ReadHex{
private String textName;
private String hex;

public ReadHex(String textNameIn){
textName=textNameIn;
this.readHex();
}

private void readHex(){
try{
FileReader fr=new FileReader(textName);
BufferedReader br=new BufferedReader(fr);
boolean off=false;
while(!off){
String hextemp=br.readLine();
if(hextemp==null)
off=true;
else
hex=hex+hextemp;
}
br.close();
}catch(IOException e){
System.out.println("Error - "+e.toString());
}
}

//返回得到的字符串
public String getHex(){
return hex;
}
}

//将十六进制码转换为十进制
class ConHex{
private String hex;
private int[] out;

public ConHex(String hexIn){
hex=hexIn;
this.conHex();
}

private void conHex(){
try{
for(int i=0;i+1<hex.length();i+=2){
String sub=hex.substring(i,i+2);
out[i]=Integer.parseInt(sub,16);
}
}catch(Exception e){
System.out.println("Error - "+e.getMessage());
}
}

//返回十进制数组
public int[] getOut(){
return out;
}
}

//输出十进制数
public class HexConverter{
public static void main(String[] args){

ReadHex rh=new ReadHex(args[0]);
ConHex ch=new ConHex(rh.getHex());
int[] outPut=ch.getOut();
for(int i=0;i<outPut.length;i++){
System.out.print(outPut[i]+" ");
}
}
}

请看看这程序哪有问题啊,怎么运行时就出异常

------解决方案--------------------
代码我大概修改了一下 你看看 都有注释。


package com.chang.test;

import java.io.*;

//读取含十六进制码的文本文件
class ReadHex {
private String textName;

//首先在这把 hex 初始化为空。
private String hex = "";

public ReadHex(String textNameIn) {
textName = textNameIn;
this.readHex();
}

private void readHex() {
try {
FileReader fr = new FileReader(textName);
BufferedReader br = new BufferedReader(fr);
boolean off = false;
while (!off) {
String hextemp = br.readLine();
if (hextemp == null)
off = true;
else
hex = hex + hextemp;
}
br.close();
} catch (IOException e) {
System.out.println("Error - " + e.toString());
}
}

// 返回得到的字符串
public String getHex() {
return hex;
}
}

// 将十六进制码转换为十进制
class ConHex {
private String hex;
private int[] out;

public ConHex(String hexIn) {
hex = hexIn;
this.conHex();
}

private void conHex() {

//在这把 out 初始化。
int temp = hex.length()/2 + 1;
out = new int[temp];
//用j来表示数组的下标,i 每次都是在加 2,不能用来当作数据out的下标。
int j = 0;

try {
//如果是基数,则要判断 == 的情况。
for (int i = 0; i + 1 <= hex.length(); i += 2) {
String sub = "";
if(i + 1 == hex.length()) {
//这个地方取到一个16进制数,看你想怎么判断了。可以在前面加0,或这在后面加0;默认前面加0。
sub = hex.substring(i, i + 1);
} else {
sub = hex.substring(i, i + 2);
}


out[j] = Integer.parseInt(sub, 16);
//j++ 数据下标。
j++;
}
} catch (Exception e) {
e.printStackTrace();
System.out.println("Error - " + e.getMessage());
}
}

// 返回十进制数组
public int[] getOut() {
return out;
}
}

// 输出十进制数
public class HexConverter {
public static void main(String[] args) {
ReadHex rh = new ReadHex(args[0]);
ConHex ch = new ConHex(rh.getHex());
int[] outPut = ch.getOut();
for (int i = 0; i < outPut.length; i++) {