一、java.lang.NumberFormatException 错误及解决办法
- 首先根据错误提示我们可以知道是数字格错误,具体是哪个类的哪个方法的哪一行的错误了,看下面错误堆栈,定位到错误的具体位置。
- 在实验中定位到下面语句出错,分析后发现是由于参考实验指导手册中的代码在将字符串转为数字时字符串中出现了空格,导致转换出错。
magicSquare[i][j] = Integer.parseInt(array[i].split("\t")[j]);
- 解决办法,将语句改为下面格式即可解决,或者对字符串进行处理,消除字符串中的空格也可解决问题。
magicSquare[i][j] = Integer.parseInt(array[i].split("\t")[j].trim());
二、Java中的int和String的几种转换方式
承接上文,在解决错误后查询了其他int和String转换的几种方法,总结如下:
1.String转int有两种方式
(1)Integer.parseInt(str)
(2)Integer.valueOf(str).intValue()
2.int转String有三种方式
(1)num + “”
(2)String.valueOf(num)
(3)Integer.toString(num)
三、对文件的读写操作总结
1.对文件的读操作
// 构建字节输入流对象,参数为文件名
FileInputStream fin = new FileInputStream(fileName);
byte[] temp = new byte[fin.available()];
// 从输入流读取数据
if(fin.read(temp)==0){
System.out.println("空文件");
return false;
}
String myLine=new String(temp);
2.对文件的写操作
String filename = "src\\P1\\txt\\6.txt";
FileOutputStream fout = new FileOutputStream(filename);
String tempString;
byte[] tempByte;
tempString = "Hello World\n";
tempByte = tempString.getBytes(StandardCharsets.UTF_8);
fout.write(tempByte);
四、Java动态二维数组
1.用map来实现
public static Map<Double, List<Double>> create(double row, double column) {
Map<Double, List<Double>> doubleMap = new HashMap<Double, List<Double>>();
for (double x = 0; x < row; x++) {
for (double y = 0; y < column; y++) {
doubleMap.put(x, new ArrayList<Double>());
}
}
return doubleMap;
}
2.用List来实现
public static void main(String args[]) {
List<List<Integer>> list = new ArrayList();
List<Integer> a1 = new ArrayList<Integer>();
List<Integer> a2 = new ArrayList<Integer>();
List<Integer> a3 = new ArrayList<Integer>();
list.add(a1);
list.add(a2);
list.add(a3);
a1.add(1);
a1.add(11);
a2.add(2);
a3.add(3);
a3.add(31);
for (int i = 0; i < list.size(); ++i) {
for (int j = 0; j < list.get(i).size(); ++j)
System.out.println(list.get(i).get(j));
}
}