Java第六次作业

(一)学习总结

1.用思维导图对本周的学习内容进行总结。

  • 异常处理

  • 泛型与集合

    参考资料: XMind

2.当程序中出现异常时,JVM会依据方法调用顺序依次查找有关的错误处理程序。可使用printStackTrace 和getMessage方法了解异常发生的情况。阅读下面的程序,说明printStackTrace方法和getMessage 方法的输出结果分别是什么?并分析异常的传播过程。

      public class PrintExceptionStack {
            public static void main( String args[] )
            {
                 try {
                     method1();
                  } catch ( Exception e ) {
                     System.err.println( e.getMessage() + "\n" );
                     e.printStackTrace();
                  }
            }
           public static void method1() throws Exception
           {
              method2();
           }
           public static void method2() throws Exception
           {
              method3();
           }
           public static void method3() throws Exception
           {
              throw new Exception( "Exception thrown in method3" );
           }
        }
  • getMessage输出的结果:

       Exception thrown in method3
    
  • printStackTrace输出的结果:

     java.lang.Exception: Exception thrown in method3
     	at PrintExceptionStack.method3(PrintExceptionStack.java:21)
     	at PrintExceptionStack.method2(PrintExceptionStack.java:17)
     	at PrintExceptionStack.method1(PrintExceptionStack.java:13)
     	at PrintExceptionStack.main(PrintExceptionStack.java:5)
    
  • String getMessage():返回此throwable详细信息字符串
    void printStackTrace():将此 throwable对象的堆栈跟踪输出至错误输出流

3.阅读下面程序,分析程序的运行结果,解释产生错误的原因,如果删除的是books集合的最后一个对象,运行的结果又是什么?你能对此作出解释吗?如果在遍历时非要删除集合中的元素,应如何实现?

import java.util.*;
public class Test
{
    public static void main(String[] args) 
    {
        Collection<String> books = new ArrayList<String>();
        books.add("One book");
        books.add("Two book");
        books.add("Three book");
        System.out.println("原始元素之后:"+books);
        Iterator<String> it = books.iterator();
        while(it.hasNext())
        {
            String book = (String)it.next();
            System.out.println(book);
            if (book.equals("One book"))
            {
                books.remove(book);
            }
        }
        System.out.println("移除元素之后:"+books);
    }
}
  • 第一条输出语句可以输出列表,结果为:

     原始元素之后:[One book, Two book, Three book]
    
  • 第二条输出语句有错,不能输出:

    Exception in thread "main" One book
    java.util.ConcurrentModificationException
    	at java.util.ArrayList$Itr.checkForComodification(ArrayList.java:886)
    	at java.util.ArrayList$Itr.next(ArrayList.java:836)
    	at Test.main(Test.java:14)
    
  • 删除最后一个对象,运行结果为:

       原始元素之后:[One book, Two book, Three book]
      Exception in thread "main" One book
      Two book
      Three book
      java.util.ConcurrentModificationException
      	at java.util.ArrayList$Itr.checkForComodification(ArrayList.java:886)
      	at java.util.ArrayList$Itr.next(ArrayList.java:836)
      	at Test.main(Test.java:14)
    
  • 第二条语句有错的原因:

       删除语句 books.remove(book);有错,用Iterator删除语句时,直接使用remove()方法即可,但是不能用集合对象的remove()方法,应该用迭代器的remove()方法,否则集合本身的内容被破坏掉,迭代将出现错误,停止输出。
    
  • 修改之后的程序:

           import java.util.*;
      public class Test
      {
          public static void main(String[] args) 
          {
              Collection<String> books = new ArrayList<String>();
              books.add("One book");
              books.add("Two book");
              books.add("Three book");
              System.out.println("原始元素之后:"+books);
              Iterator<String> it = books.iterator();
              while(it.hasNext())
              {
                  String book = it.next();
                  System.out.println(book);
                  if (book.equals("One book"))
                  {
                      it.remove();
                  }
              }
              System.out.println("移除元素之后:"+books);
          }
      }
    
  • 正确的运行结果:

      原始元素之后:[One book, Two book, Three book]
      One book
      Two book
      Three book
      移除元素之后:[Two book, Three book]
    

4.HashSet存储的元素是不可重复的。运行下面的程序,分析为什么存入了相同的学生信息?如果要去掉重复元素,应该如何修改程序。

import java.util.*;
class Student {
    String id;  
    String name;
    public Student(String id, String name) {
        this.id = id;
        this.name = name;
    }
    public String toString() {
        return "Student id=" + id + ", name=" + name ;
    }
}
public class Test
{
    public static void main(String[] args) 
    {
        HashSet<Student> set = new HashSet<Student>();
        set.add(new Student("1","Jack"));
        set.add(new Student("2","Rose"));
        set.add(new Student("2","Rose"));
        System.out.println(set);                
    }
}
  • 存入相同元素的原因:

      要想去掉重复元素,必须进行对象是否重复的判断,实现判断的方法就是覆写Object类中的equals()方法,才能完成对象是否相等的判断,HashSet依靠hashCode()方法和equals()方法完成重复元素判断,因此还需覆写 hashCode()方法。    
    
  • 修改后的程序:

              import java.util.*;
              class Student {
              	String id;
              	String name;
              	public Student(String id, String name) {
              		this.id = id;
              		this.name = name;
              	}
              	public int hashCode() {
              		final int prime = 31;
              		int result = 1;
              		result = prime * result + ((id == null) ? 0 : id.hashCode());
              		result = prime * result + ((name == null) ? 0 : name.hashCode());
              		return result;
              	}
              	public boolean equals(Object obj) {
              		if (this == obj)
              			return true;
              		if (obj == null)
              			return false;
              		if (getClass() != obj.getClass())
              			return false;
              		Student other = (Student) obj;
              		if (id == null) {
              			if (other.id != null)
              				return false;
              		} else if (!id.equals(other.id))
              			return false;
              		if (name == null) {
              			if (other.name != null)
              				return false;
              		} else if (!name.equals(other.name))
              			return false;
              		return true;
              	}
              	public String toString() {
              		return "Student id=" + id + ", name=" + name;
              	}
              }
              import java.util.HashSet;
              public class Test {
              	public static void main(String[] args) {
              		HashSet<Student> set = new HashSet<Student>();
              		set.add(new Student("1", "Jack"));
              		set.add(new Student("2", "Rose"));
              		set.add(new Student("2", "Rose"));
              		System.out.println(set);
              	}
              }
    

5.其他需要总结的内容。

  • 菜单格式

        for (; ; ) {
          			System.out.println("请输入需要的操作:\n");
          			int m = input.nextInt();
          			switch (m) {
          			case (1):
          			break;
          			}
          		}
           
       Scanner input = new Scanner(System.in);
          while (true) {
          			System.out.println("------菜单------");
          			System.out.println("1.");
          			String str1 = "0";
          			try {
          				str1 = input.nextLine();
          			} catch (Exception ex) {
          				str1 = "3";
          				input = new Scanner(System.in);
          			}
          			switch (str1) {
          			case "1":
                         break;
                         }
                       }
    

(二)实验总结

1.模拟KTV点歌系统

分别用LinkedList和ArrayList集合,实现一个模拟KTV点歌系统的程序。实现以下功能:
(1)显示歌曲列表
(2)添加歌曲到列表
(3)删除歌曲
(4)将歌曲置顶
(5)将歌曲前移一位
(6)退出
题目扩展:歌曲包括曲名、演唱者。增加排序显示歌曲列表功能。

  • 程序设计思路:只是单纯的完成题目括展前的实现功能,参考教材,
    题目扩展,设置一个Person类,定义歌曲名name和歌手名per,用TreeSet排序输出
    问题1:添加菜单之后,运行时,需要输入内容的语句都不能显示
    原因:输入语句格式错误,菜单没有写for( ; ; )语句
    解决方案:

      	String str3 = input.nextLine();
    

改为

    	String str3 = input.next();

问题2:扩展题目运行时,删除语句不能实现,置顶语句不能把原位置的语句删除,前移语句出错,数组下标越界

     Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: -2, Size: 3
    	at java.util.ArrayList.rangeCheckForAdd(ArrayList.java:646)
    	at java.util.ArrayList.add(ArrayList.java:458)
    	at ArraysList.main(ArraysList.java:51)

原因: 表示下标的语句:

    int j = allList.indexOf(new Person(d, e));

表示删除的语句:

	String str4 = input.next();
	allList.remove(str4);

解决方案:未解决,尝试多种方法,改不对

2.模拟微博用户注册

用HashSet实现一个模拟微博用户注册的程序。用户输入用户名、密码、确认密码、生日(格式yyyy-mm-dd)、手机号码(11位,13、15、17、18开头)、邮箱信息进行微博的注册。要求对用户输入的信息进行验证,输入信息正确后,验证是否重复注册,如果不是则注册成功,否则注册失败。
提示:
(1)设计一个用户类存储用户注册信息
(2)设计一个校验信息类,定义校验方法完成对输入信息的校验。学习使用正则表达式完成对生日、手机号码和邮箱的验证。
(3)设计一个用户注册类模拟注册过程。用HashSet存储用户数据列表,定义一个initData()方法添加初始用户信息。在main方法中完成用户注册功能。

  • 程序设计思路:设计三个类,一个Person类,定义用户的各个属性;一个Check类,验证两次密码对否一样,生日,手机号码,邮箱信息格式是否符合;一个HashSet类存储信息,参考教材393正则表达式的使用方法
    问题1: new HashSet();显示HashSet这有错

      public class HashSet {
           public static void main(String[] args){
          	 Scanner input = new Scanner(System.in);
          	 Set<String>allSet = new HashSet<String>();
    

原因: HashSet不是通用的,不能用参数将它实例化,类名定义的HashSet在实例化的时候有冲突
解决方案: 将类名修改为其它的,不能和HashSet一样
问题2: 写程序过程中出现小错误,选中错误,自己改好,程序显示没错之后,只有HashSet类可以运行需要输入的没内容,其他类没作用,输完之后会显示

    Exception in thread "main" java.lang.NullPointerException
    	at java.util.Calendar.setTime(Calendar.java:1770)
    	at java.text.SimpleDateFormat.format(SimpleDateFormat.java:943)
    	at java.text.SimpleDateFormat.format(SimpleDateFormat.java:936)
    	at java.text.DateFormat.format(DateFormat.java:345)
    	at Person.toString(Person.java:69)
    	at java.lang.String.valueOf(String.java:2979)
    	at java.lang.StringBuilder.append(StringBuilder.java:131)
    	at java.util.AbstractCollection.toString(AbstractCollection.java:462)
    	at java.lang.String.valueOf(String.java:2979)
    	at java.io.PrintStream.println(PrintStream.java:821)
    	at HashSetTest.main(HashSetTest.java:31)

数据无法存储和输出
解决方案:未解决

(三)代码托管

码云commit历史截图
上传实验项目代码到码云,在码云项目中选择“统计-commits”,设置搜索时间段,搜索本周提交历史,并截图。