Java程序设计2023-第五次上机练习

7-1jmu-Java-06异常-01-常见异常

自行编码产生常见异常。
main方法
事先定义好一个大小为5的数组。
根据屏幕输入产生相应异常。
提示:可以使用System.out.println(e)打印异常对象的信息,其中e为捕获到的异常对象。
输入说明:
arr 代表产生访问数组是产生的异常。然后输入下标,如果抛出ArrayIndexOutOfBoundsException异常则显示,如果不抛出异常则不显示。
null,产生NullPointerException
cast,尝试将String对象强制转化为Integer对象,产生ClassCastException。
num,然后输入字符,转化为Integer,如果抛出NumberFormatException异常则显示。
其他,结束程序。
输入样例:

arr 4
null
cast
num 8
arr 7
num a
other

输出样例:

java.lang.NullPointerException
java.lang.ClassCastException: class java.lang.String cannot be cast to class java.lang.Integer (java.lang.String and java.lang.Integer are in module java.base of loader 'bootstrap')
java.lang.ArrayIndexOutOfBoundsException: Index 7 out of bounds for length 5
java.lang.NumberFormatException: For input string: "a"

可以尝试捕获多个异常

import java.util.*;
public class Main{
    public static void main(String []args){
        Scanner in=new Scanner(System.in);
        int []a=new int[5];
        String str;
        while(true){
            str=in.nextLine();
            String []s=str.split("\\s+");
            if(s[0].equals("arr")){
                try{
                    a[Integer.parseInt(s[1])]=1;
                }catch(Exception e){
                    System.out.println(e);
                }
            }else if(s[0].equals("null")){
                System.out.println("java.lang.NullPointerException");
            }else if(s[0].equals("cast")){
                try{
                    Object c=new String();
                    System.out.println((Integer)c);
                    
                }catch(Exception e){
                    System.out.println(e);
                }
            }else if(s[0].equals("num")){
                try{
                    Integer tmp=Integer.parseInt(s[1]);
                }catch(Exception e){
                    System.out.println(e);
                }
            }else break;
        }
    }
}

7-2jmu-Java-06异常-02-使用异常机制处理异常输入

使用异常处理输入机制,让程序变得更健壮。
main方法:
输入n,创建大小为n的int数组。
输入n个整数,放入数组。输入时,有可能输入的是非整型字符串,这时候需要输出异常信息,然后重新输入。
使用Arrays.toString输出数组中的内容。
输入样例:

5
1
2
a
b
4
5
3

输出样例:

java.lang.NumberFormatException: For input string: "a"
java.lang.NumberFormatException: For input string: "b"
[1, 2, 4, 5, 3]
import java.util.*;
public class Main{
    public static void main(String []args){
        Scanner in=new Scanner(System.in);
        String str=in.nextLine();
        int n=Integer.parseInt(str);
        int []a=new int[n];
        int k=0;
        while(k<n){
            try{
                str=in.nextLine();
                a[k]=Integer.parseInt(str);
                k++;
            }catch(Exception e){
                System.out.println(e);
            }
        }
        System.out.println(Arrays.toString(a));
    }
}

7-3jmu-Java-06异常-04-自定义异常(综合)

定义IllegalScoreException异常类,代表分数相加后超出合理范围的异常。该异常是checked exception,即希望该异常一定要被捕获处理。
定义IllegalNameException异常类,代表名字设置不合理的异常。该异常是unchecked exception
定义Student类。
属性:
private String name;
private int score;
方法:
toString //自动生成
setter/getter //自动生成
改造setName //如果姓名首字母为数字则抛出IllegalNameException
public int addScore(int score) //如果加分后分数<0 或>100,则抛出IllegalScoreException,加分不成功。
main方法
输入new则新建学生对象。然后输入一行学生数据,格式为姓名 年龄,接着调用setName,addScore。否则跳出循环。
setName不成功则抛出异常,并打印异常信息,然后继续下一行的处理。
addScore不成功则抛出异常,并打印异常信息,然后继续下一行的处理。如果2、3都成功,则打印学生信息(toString)
如果在解析学生数据行的时候发生其他异常,则打印异常信息,然后继续下一行的处理。
Scanner也是一种资源,希望程序中不管有没有抛出异常,都要关闭。关闭后,使用System.out.println(“scanner closed”)打印关闭信息
注意:使用System.out.println(e);打印异常信息,e为所产生的异常。

输入样例:

new
zhang 10
new
wang 101
new
wang30
new
3a 100
new
wang 50
other

输出样例:

Student [name=zhang, score=10]
IllegalScoreException: score out of range, score=101
java.util.NoSuchElementException
IllegalNameException: the first char of name must not be digit, name=3a
Student [name=wang, score=50]
scanner closed
import java.util.*;
class IllegalScoreException extends Exception{
    private int score;
    public IllegalScoreException(int a){
        super("IllegalScoreException: score out of range, score=");
        score=a;
    }
    public String toString() {
        return this.getMessage()+score;
    }
}
class IllegalNameException extends Exception{
    private String name;
    public IllegalNameException(String a){
        super("IllegalNameException: the first char of name must not be digit, name=");
        name=a;
    }
    public String toString() {
        return this.getMessage()+name;
    }
}
class Student{
    private String name="";
    private int score=0;
    public String toString(){
        return "Student [name="+name+", score="+score+"]";
    }
    public void setName(String a)throws IllegalNameException{
        String first=a.substring(0,1);
        if(first.compareTo("0")>=0&&first.compareTo("9")<=0)throw new IllegalNameException(a);
        name=a;
    }
    public int addScore(int score)throws IllegalScoreException{
        if(score+this.score<0||score+this.score>100)throw new IllegalScoreException(score);
        this.score+=score;
        return this.score;
    }
}
public class Main{
    public static void main(String []args){
        Scanner in=new Scanner(System.in);
        String str;
        while(true){
            str=in.nextLine();
            if(str.equals("new")){
                str=in.nextLine();
                String []s=str.split("\\s+");
                if(s.length==2){
                    Student st=new Student();
                    try{
                        st.setName(s[0]);
                        st.addScore(Integer.parseInt(s[1]));
                        System.out.println(st);
                    }catch(IllegalNameException e){
                        System.out.println(e);
                    }catch(IllegalScoreException e){
                        System.out.println(e);
                    }catch(Exception e){
                        System.out.println(e);   
                    }
                }else System.out.println("java.util.NoSuchElementException");
                
            }else break;
        }
        System.out.println("scanner closed");
    }
}

7-4jmu-Java-02基本语法-08-ArrayList入门

本习题主要用于练习如何使用ArrayList来替换数组。
新建1个ArrayList strList用来存放字符串,然后进行如下操作。

提示: 查询Jdk文档中的ArrayList。
注意: 请使用System.out.println(strList)输出列表元素。

输入格式
输入: 若干字符串,放入strList。直到输入为!!end!!时,结束输入。

在strList头部新增一个begin,尾部新增一个end。

输出列表元素

输入: 字符串str

判断strList中有无包含字符串str,如包含输出true,否则输出false。并且输出下标,没包含返回-1。

在strList中从后往前找。返回其下标,找不到返回-1。

移除掉第1个(下标为0)元素,并输出。然后输出列表元素。

输入: 字符串str

将第2个(下标为1)元素设置为字符串str.

输出列表元素

输入: 字符串str

遍历strList,将字符串中包含str的元素放入另外一个ArrayList strList1,然后输出strList1。

在strList中使用remove方法,移除第一个和str相等的元素。

输出strList列表元素。

使用clear方法,清空strList。然后输出strList的内容,size()与isEmpty(),3者之间用,连接。

输入样例:

a1 b1 3b a2 b2 b1 12b c d !!end!!
b1
second
b

输出样例:

[begin, a1, b1, 3b, a2, b2, b1, 12b, c, d, end]
true
2
6
begin
[a1, b1, 3b, a2, b2, b1, 12b, c, d, end]
[a1, second, 3b, a2, b2, b1, 12b, c, d, end]
[3b, b2, b1, 12b]
[a1, second, 3b, a2, b2, b1, 12b, c, d, end]
[],0,true

ArrayList

import java.util.*;
public class Main{
    public static void main(String []args){
        Scanner in=new Scanner(System.in);
        String str=in.nextLine();
        String []s=str.split("\\s+");
        ArrayList<String> strList=new ArrayList<String>();
        for(int i=0;i<s.length-1;i++){
            strList.add(s[i]);
        }
        strList.add(0,"begin");
        strList.add("end");
        System.out.println(strList);
        
        str=in.nextLine();
        boolean f=false;
        for(int i=0;i<strList.size();i++){
            if(strList.get(i).equals(str)){
                f=true;
                System.out.println(f);
                System.out.println(i);
                break;
            }
        }
        if(f==false){
            System.out.println(f);
            System.out.println(-1);
        }
        f=false;
        for(int i=strList.size()-1;i>=0;i--){
            if(strList.get(i).equals(str)){
                f=true;
                System.out.println(i);
                break;
            }
        }
        if(f==false){
            System.out.println(-1);
        }
        System.out.println(strList.get(0));
        strList.remove(0);
        System.out.println(strList);
        
        str=in.nextLine();
        strList.remove(1);
        strList.add(1,str);
        System.out.println(strList);

        str=in.nextLine();
        ArrayList<String> strList1=new ArrayList<String>();
        for(int i=0;i<strList.size();i++){
            if(strList.get(i).contains(str)){
                strList1.add(strList.get(i));
            }
        }
        System.out.println(strList1);
        for(int i=0;i<strList.size();i++){
            if(strList.get(i).equals(str)){
                strList.remove(i);
                break;
            }
        }
        System.out.println(strList);
        strList.clear();
        System.out.println(strList+","+strList.size()+","+strList.isEmpty());
    }
}

7-5jmu-Java-m06 统计一篇英文文章中出现的不重复单词的个数

输入一篇英文文章,碰到"!!!"的时候停止,输出文章中出现的不重复单词的个数(注意:单词不区分大小写,如:The和the为一个单词)

输入格式:
一篇英文文章,以"!!!"结尾

输出格式:
不重复单词的个数

输入样例:

Unmanned aerial vehicles have been adopted in the inspection of violations Procurators will file public interest litigations against perpetrators who will need to replant trees take down illegal buildings control pollution and compensate environment-related losses  
The Yellow River is the second longest river in China It originates in the northwestern province of Qinghai and runs through nine provinces and autonomous regions in western central north and eastern China  
!!!!!

输出样例:

55

HashMap

import java.util.*;
public class Main{
    public static void main(String []args){
        Scanner in=new Scanner(System.in);
        String str;
        Map<String,Integer> word=new HashMap<String,Integer>();
       while(true){
           if((str=in.nextLine()).equals("!!!!!"))break;
           String []s=str.split("\\s+");
           for(int i=0;i<s.length;i++){
               String s1=s[i].toLowerCase ();
               if(word.get(s1)==null)word.put(s1,1);
               else word.put(s1,word.get(s1)+1);
            }
       }

        System.out.println(word.size());
    }
}

7-6sdut-String+array(LinkedHashMap) 读中国载人航天史,汇航天员数量,向航天员致敬(1)

输入格式:
每次航天飞船的编号为一行读入数据,分别读入每次飞上太空的航天英雄的姓名,名字中间有一个空格分隔。
最后一行为“end“,表示输入结束。

提示:目前,中国航天员的数量小于20。
输出格式:
以出征太空的先后顺序,统计航天英雄们出征太空的次数。
每位航天员占一行,航天员姓名与出征次数中间有一个空格。
输入样例:

杨利伟
费俊龙 聂海胜
翟志刚 景海鹏 刘伯明
景海鹏 刘旺 刘洋
聂海胜 张晓光 王亚平
景海鹏 陈东
end

输出样例:

杨利伟 1
费俊龙 1
聂海胜 2
翟志刚 1
景海鹏 3
刘伯明 1
刘旺 1
刘洋 1
张晓光 1
王亚平 1
陈东 1

LinkedHashMap

import java.util.*;
public class Main{
    public static void main(String []args){
        Scanner in=new Scanner(System.in);
        String str;
        Map<String,Integer> astronaunt=new LinkedHashMap<String,Integer>();
       while(true){
           if((str=in.nextLine()).equals("end"))break;
           String []s=str.split("\\s+");
           for(int i=0;i<s.length;i++){
               if(astronaunt.get(s[i])==null)astronaunt.put(s[i],1);
               else astronaunt.put(s[i],astronaunt.get(s[i])+1);
            }
       }
        for (String i : astronaunt.keySet()) {
            System.out.println(i +" "+astronaunt.get(i));
        }
    }
}

7-7jmu-Java-05集合-01-ListIntegerStack

输入样例

5
1 3 5 7 -1
2

输出样例

1
3
5
7
-1
-1,false,5
[1, 3, 5, 7, -1]
-1
7
5,false,3
[1, 3, 5]
import java.util.*;
interface IntegerStack{
    public Integer push(Integer item); // 如item为null,则不入栈直接返回null。否则直接入栈,然后返回item。
    public Integer pop(); // 出栈,如栈为空,则返回null。
    public Integer peek(); // 获得栈顶元素,如栈顶为空,则返回null。注意:不要出栈
    public boolean empty(); // 如果栈为空返回true
    public int size();  // 返回栈中元素数量
}
class ArrayListIntegerStack implements IntegerStack{
    ArrayList<Integer> list;
    public ArrayListIntegerStack(){
        list=new ArrayList<Integer>();
    }
    public Integer push(Integer item){
        if(item==null)return null;
        list.add(item);
        return item;
    } // 如item为null,则不入栈直接返回null。否则直接入栈,然后返回item。
    public Integer pop(){
        if(list.size()==0)return null;
        Integer a=list.get(list.size()-1);
        list.remove(list.size()-1);
        return a;
    } // 出栈,如栈为空,则返回null。
    public Integer peek(){
        if(list.size()==0)return null;
        Integer a=list.get(list.size()-1);
        return a;
    }// 获得栈顶元素,如栈顶为空,则返回null。注意:不要出栈
    public boolean empty(){
        if(list.size()==0)return true;
        return false;
    } // 如果栈为空返回true
    public int size(){
        return list.size();
    }  // 返回栈中元素数量
    public String toString(){
        return list.toString();
    }
}
public class Main{
    public static void main(String []args){
        ArrayListIntegerStack st=new ArrayListIntegerStack();
        Scanner in=new Scanner(System.in);
        int n=in.nextInt();
        int x;
        for(int i=0;i<n;i++){
            x=in.nextInt();
            System.out.println(st.push(x));
        }
        System.out.println(st.peek()+","+st.empty()+","+st.size());
        System.out.println(st);
        x=in.nextInt();
        for(int i=0;i<x;i++){
            System.out.println(st.pop());
        }
        System.out.println(st.peek()+","+st.empty()+","+st.size());
        System.out.println(st);
    }
}

7-8约瑟夫环问题

约瑟夫环是一个数学的应用问题:已知n个人(以编号a,b,c…分别表示)围坐在一张圆桌周围。从编号为1的人开始报数,数到m的那个人出列;他的下一个人又从1开始报数,数到m的那个人又出列;依此规律重复下去,直到圆桌周围的人全部出列。

输入格式:
固定为2行,第一行为m,第二行为n个人的名称列表,用英文字母代表,元素直接使用英文逗号 , 分开

输出格式:
一行,为出列元素序列,元素之间使用英文逗号 , 分开【注意:末尾元素后没有逗号】

输入样例:
在这里给出一组输入。例如:

3
a,b,c,d,e,f,g

输出样例:
在这里给出相应的输出。例如:

c,f,b,g,e,a,d
import java.util.*;
public class Main{
    public static void main(String []args){
        Scanner in=new Scanner(System.in);
        String str=in.nextLine();
        int m=Integer.parseInt(str);
        str=in.nextLine();
        String []person=str.split(",");
        int n=person.length;
        boolean []f=new boolean[n];
        for(int i=0;i<n;i++)f[i]=false;
        int cnt=0;
        int now=-1;
        int k=0;
        while(cnt<n){
            now++;now%=n;
            if(f[now]==false)k++;
            if(k==m){
                if(cnt!=0)System.out.printf(",");
                System.out.print(person[now]);
                f[now]=true;
                cnt++;
                k=0;
            }
        }
    }
}

7-9jmu-java-m02-使用列表管理姓名

输入若干行字符串,每行代表一个姓名,依次存入数组列表(类型为ArrayList)nameList中,每个名字只能加入一次。
现在nameList相当于一个存储姓名的数据库,可以对nameList进行适当的操作,以实现姓名管理系统。
输入与输出格式:
输入不定个数的姓名字符串,直到遇到end为止,依次将字符串存入数组列表nameList。注意:每个名字只能存1次。
输出nameList中所有元素。(请使用System.out.println(nameList)输出列表元素。)
接下来:
输入下标i
输入字符串x,然后加到nameList的第i个位置。
输入下标j,然后移除下标为j的姓名。
输出nameList中所有元素。
最后:
输入字符串name1
输入字符串name2
输出字符串name1所在下标k(从前往后找)。
如果k>=0,将name2放在nameList中下标k位置处(即,替换掉原来k位置的元素)。否则,如果k=-1,将name2直接添加nameList最后一个元素之后。
最后输出nameList。
输入样例1:

Tom
Jerry
tom
Tom
Zhang san
Li Si
Zhang san
li si
end
3
Sunxingzhe
1
tom
Jack

输出样例1:

[Tom, Jerry, tom, Zhang san, Li Si, li si]
[Tom, tom, Sunxingzhe, Zhang san, Li Si, li si]
k=1
[Tom, Jack, Sunxingzhe, Zhang san, Li Si, li si]
import java.util.*;
public class Main{
    public static void main(String []args){
        Scanner in=new Scanner(System.in);
        ArrayList<String> list=new ArrayList<String>();
        String str;
        while(true){
            str=in.nextLine();
            if(str.equals("end"))break;
            int len=list.size();
            boolean f=false;
            for(int i=0;i<len;i++){
                if(list.get(i).equals(str)){
                    f=true;
                    break;
                }
            }
            if(f==false)list.add(str);
        }
        System.out.println(list);
        
        str=in.nextLine();
        int p=Integer.parseInt(str);
        str=in.nextLine();
        list.add(p,str);
        
        str=in.nextLine();
        p=Integer.parseInt(str);
        list.remove(p);
        System.out.println(list);

        str=in.nextLine();
        String str2=in.nextLine();
        int k=-1;
        for(int i=0;i<list.size();i++){
            if(list.get(i).equals(str)){
                k=i;break;
            }
        }
        System.out.println("k="+k);
        
        if(k==-1)list.add(str2);
        else{
            list.remove(k);
            list.add(k,str2);
        }
        System.out.println(list);
        
    }
}

7-10jmu-java-m02-综合:使用列表管理个人信息

现在想要使用列表(ArrayList或LinkedList)来管理个人信息。
首先,输入字符串n-x-y。n代表所要处理的数据的数量,x代表姓,y代表名。
然后输入n个人的信息,每一行代表一个人的信息。每行字符串格式为"姓-名-成绩-编号",以-作为分隔符。
将所有姓为x的字符串放入数组列表list1中。然后,输出list1。
进一步地将list1中的名字为y(忽略大小写)的字符串取出放入list2中。然后,输出list2。
最后,对list2中的字符串按成绩进行降序排序并输出。
输入格式:
第一行输入n-x-y
下面输入n行字符串,格式为"姓-名-成绩-编号"
输出格式:
格式化输出的多个人的信息
输入样例:

8-zhang-san
zhang-san-99-1
li-si-70-2
zhang-San-65-3
zhang-fei-70-4
zhang-SAn-101-5
Li-si-99-6
li-SI-80-7
Zhang-san-56-8

输出样例:

[zhang-san-99-1, zhang-San-65-3, zhang-fei-70-4, zhang-SAn-101-5]
[zhang-san-99-1, zhang-San-65-3, zhang-SAn-101-5]
[zhang-SAn-101-5, zhang-san-99-1, zhang-San-65-3]
import java.util.*;
public class Main{
    public static void main(String []args){
        Scanner in=new Scanner(System.in);
        ArrayList<String> list1=new ArrayList<String>();
        ArrayList<String> list2=new ArrayList<String>();
        String str=in.nextLine();
        String []origin=str.split("-");
        int n=Integer.parseInt(origin[0]);
        for(int i=0;i<n;i++){
            str=in.nextLine();
            String []s=str.split("-");
            if(s[0].equals(origin[1])){
                list1.add(str);
                if(s[1].toLowerCase().equals(origin[2].toLowerCase())){
                    list2.add(str);
                }
            }
        }
        System.out.println(list1);
        System.out.println(list2);
        for(int i=0;i<list2.size();i++){
            for(int j=0;j<list2.size()-1;j++){
                String a=list2.get(j);
                String []sa=a.split("-");
                String b=list2.get(j+1);
                String []sb=b.split("-");
                
                if(Integer.parseInt(sa[2])<Integer.parseInt(sb[2])){
                    String tmp=b;
                    list2.remove(j+1);
                    list2.add(j,tmp);
                }
            }
        }
        System.out.println(list2);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值