《Java程序设计》第 6 周学习总结

教材学习内容总结

  • 第七章要点:
    • 要点1:内部类;
    • 要点2:匿名类:和子类有关、和接口有关;
    • 要点3:异常类:try-catch 语句、自定义异常类;
    • 要点4:断言、应用举例。

  • 第十章要点:
    • 要点1:File 类;
    • 要点2:文件字节输入流、输出流、;
    • 要点3:缓冲流、随机流、数组流、数据流、对象流;
    • 要点4:序列化与对象克隆;
    • 要点5:使用 Scanner 解析文件;
    • 要点6:文件对话框;
    • 要点7:带进度条的输入流;
    • 要点8:文件锁、应用举例。

代码调试中的问题和解决过程

1. 编译运行时,跳过 Scanner.nextLine() 语句。

编译如下代码

import java.util.Scanner;
public class test {
    public static void main(String args[]) {
        System.out.println("Input the number of books:");
        Scanner reader = new Scanner(System.in);
        int num = reader.nextInt();
        System.out.println("Input the book "+num+" information of bookName");
        String name = reader.nextLine();
        System.out.println("Input the book "+num+" information of bookWriter");
        String writer = reader.nextLine();
    }
}

结果如下:

Input the number of books:
1
Input the book 1 information of bookName
Input the book 1 information of bookWriter
  • 问题1解决方案:
    原因是:nextInt()结束的回车字符被nextLine()读取了,导致接下来的 name 无法录入,跳过一行,但下面的 writer 却能正常读写。
    在第 5 行和第 6 行代码之间添加一条语句,即可正常读写:
reader.nextLine();

作用:吸收上个输入最后的回车字符(如下一个问题的 6、7 行代码)。

2. 提示 NullPointerException 错误。

代码如下:

import java.util.Scanner;

class Book {
    String bookName;
    public void setBookName(String bookName) {
        this.bookName = bookName;
    }
}

public class test {
    public static void main(String args[]) {
        System.out.println("Input the number of books:");
        Scanner reader = new Scanner(System.in);
        int num = reader.nextInt();
        reader.nextLine();
        Book book[] = new Book[3];      //[代码]
        System.out.println("Input the book "+num+" information of bookName");
        String name = reader.nextLine();
        book[0].setBookName(name);
    }
}

结果报错如下:

Input the number of books:
1
Input the information of bookName
Exception in thread "main" java.lang.NullPointerException
	at Bookshelf.main(test.java:19)

Process finished with exit code 1
  • 问题分析:
    上述代码看似没有什么问题,却提示 NullPointerException 。空指针异常,也就是说,book[0], book[1], book[2]都是没有被初始化的。
    Java在数组的定义中并不为数组元素分配内存,因此[]中不需指明数组长度,而且对于如上定义的数组是不能引用的,必须经过初始化才可以引用。
    第 16 行代码 Book book[] = new Book[3]; 实际上并没有为数组元素分配内存。

  • 问题2解决方案:
    为空指针分配内存:

//在第 16 行和第 17 行间,添加如下代码
for (int i=0; i<num; i++) {
    book[i] = new Book();
}

[代码托管]

  • 代码提交过程截图:

image.png
image.png


学习进度条

代码行数(新增/累积) 博客量(新增/累积) 学习时间(新增/累积) 重要成长
目标 5000行 30篇 400小时
第一周 322/322 1/1 23/23
第二周 520/842 3/4 25/48
第三周 458/1300 2/6 16/64
第三周 914/2214 2/8 21/85
第四周 685/2899 1/9 18/103
第五周 663/3562 2/11 20/103
  • 计划学习时间:20小时

  • 实际学习时间:20小时


参考资料

原文地址:https://www.cnblogs.com/Yogile/p/10665094.html