java-pta-代码

Posted on 2025-12-05 18:59  山河不入心呀  阅读(0)  评论(0)    收藏  举报

1. 入门-第一个PTA上Java程序

本题目要求读入若干对整数a和b,然后输出它们的和。

输入格式:

在一行中给出一对整数a和b。
以下输入样例只有两对,实际测试数据可能有多对值。

输出格式:

对每一组输入,如果a的绝对值>1000,输出|a|>1000,否则输出a+b的值。

输入样例:

18 -299
1001 -9
-1001 8

输出样例:

-281
|a|>1000
|a|>1000

参考代码

import java.util.*;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        while (sc.hasNextInt()){
            int a = sc.nextInt();
            int b = sc.nextInt();
            if(Math.abs(a)>1000){
                System.out.println("|a|>1000");
            }else {
                System.out.println(a+b);
            }
        }

    }

}

2. 古埃及探秘-金字塔

题目要求:

要求用户可以自主控制塔身的层数, 完成如下金字体样式;

输入格式:

4

输出格式:

   *
  ***
 *****
*******

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

5
8

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

    *
   ***
  *****
 *******
*********


       *
      ***
     *****
    *******
   *********
  ***********
 *************
***************

参考代码

import java.util.*;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        while (sc.hasNext()) {
            int layer = sc.nextInt();
            for (int i = 1; i <= layer; i++) {
                for (int j = 1; j <= layer - i; j++) {
                    System.out.print(" ");

                }
                for (int j = 1; j <= 2 * i - 1; j++) {
                    System.out.print("*");

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

3. 判断合法标识符

输入若干行字符串,判断每行字符串是否可以作为JAVA语法的合法标识符。

判断合法标识符的规则:由字母(含汉字)、数字、下划线“_”、美元符号“$”组成,并且首字母不能是数字。

输入格式:

输入有多行。

每行一个字符串,字符串长度不超过10个字符。

输出格式:

若该行字符串可以作为JAVA标识符,则输出“true”;否则,输出“false”。

输入样例:

abc
_test
$test
a 1
a+b+c
a’b
123
变量

输出样例:

true
true
true
false
false
false
false
true

参考代码

import java.util.*;

public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        while (in.hasNext()) {
            String s = in.nextLine();
            int flag = 0;
            for (int i = 0; i < s.length(); i++) {
                char c = s.charAt(i);
                if (i == 0) {
                    if (Character.isJavaIdentifierStart(c)) {
                        flag = 1;
                    } else {
                        flag = 0;
                        break;
                    }
                } else {
                    if (Character.isJavaIdentifierPart(c)) {
                        flag = 1;
                    } else {
                        flag = 0;
                        break;
                    }
                }
            }
            if (flag == 1) {
                System.out.println("true");
            } else {
                System.out.println("false");
            }
        }
    }
}

4. 识蛟龙号载人深潜,立科技报国志(1)

输入格式:

读入关于蛟龙号载人潜水器探测数据的多行字符串,每行字符不超过100个字符。

以"end"结束。

输出格式:

与输入行相对应的各个数字之和。

输入样例1:

2012年6月27日11时47分,中国“蛟龙”再次刷新“中国深度”——下潜7062米
6月15日,6671米
6月19日,6965米
6月22日,6963米
6月24日,7020米
6月27日,7062米
下潜至7000米,标志着我国具备了载人到达全球99%以上海洋深处进行作业的能力
end

输出样例1:

48
32
42
34
21
30
25

参考代码

import java.util.*;

public class Main {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		while (sc.hasNextLine()) {
			String line = sc.nextLine();
			if(line.equals("end"))break;
			char[] c = line.toCharArray();
			int sum = 0;
        for (char d : c) {
				if(Character.isDigit(d)) {
					sum+=Integer.parseInt(String.valueOf(d));
				}
			}
			System.out.println(sum);
		}
	}
}

5. 浮点数的精确计算

输入若干对浮点数,对每对浮点数输出其精确的和与乘积。
以下输入样例为两对浮点数输入,实际上有可能有不定对数的浮点数需要输入计算。

注1:直接使用double类型数据进行运算,无法得到精确值。
注2:输出时直接调用BigDecimal的toString方法。

输入样例:

69.1 0.02
1.99 2.01

输出样例:

69.12
1.382
4.00
3.9999

参考代码

import java.math.BigDecimal;
import java.util.*;
public class Main {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		while (sc.hasNextBigDecimal()) {
			BigDecimal n1 = sc.nextBigDecimal();
			BigDecimal n2 = sc.nextBigDecimal();
			BigDecimal sum = n1.add(n2);
			BigDecimal multiply = n1.multiply(n2);
			System.out.println(sum);
			System.out.println(multiply);
		}
	}
}

6. 学投资

小白学习了一些复利投资知识,想比较一下复利能多赚多少钱(所谓复利投资,是指每年投资的本金是上一年的本金加收益。而非复利投资是指每年资金额不包含上一年的收益,即固定投资额)。假设他每年固定投资M元(整数),每年的年收益达到P(0<P<1,double),那么经过N(整数)年后,复利投资比非复利投资多收入多赚多少钱呢?计算过程使用双精度浮点数,最后结果四舍五入输出整数(Math的round函数)。

输入格式:

M P N

输出格式:

复利收入(含本金),非复利收入(含本金),复利比非复利收入多的部分(全部取整,四舍五入)

输入样例:

10000 0.2 3

输出样例:

17280 16000 1280

参考代码

import java.util.*;
public class Main {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		int M = sc.nextInt();
		double P = sc.nextDouble();
		int N = sc.nextInt();
		double sum1 = M*(Math.pow(1+P, N));
		double sum2 = M*(1+P*N);
		double c = sum1 - sum2;
		System.out.println(Math.round(sum1)+" "+Math.round(sum2)+" "+Math.round(c));	
	}
}

7. 应用勾股定理,了解世界灿烂文明

输入格式:

输入有若干行,每行有2个数值,分别表示直角三角形的两个直角边长度,用空格分隔。

输出格式:

对应每行输入数据,输出直角三角形的斜边长度,结果保留2位小数。

输入样例:

 3 4
 2.3 3
 5 6
 10 12

输出样例:

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

5.00
3.78
7.81
15.62

参考代码

import java.util.*;

public class Main {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		while (sc.hasNextDouble()) {
			double a = sc.nextDouble();
			double b = sc.nextDouble();
			double gu = Math.sqrt(Math.pow(a, 2)+Math.pow(b, 2));
			System.out.println(String.format("%.2f", gu));
		}
	}
}

8. 计算飞行员到最近机场的距离

输入格式:

输入数据有多行。

每行为一组输入,分别是高度、角度。角度介于(0,PI/2)区间。

输出格式:

对应每行输入,求飞行员到机场的距离,保持2位小数。

输入样例:

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

1033102 0.15
10210 0.8
104320 0.7
13200  1.524
84535300 0.523

输出样例:

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

6835613.92
9916.10
123853.07
618.16
146622115.56

参考代码

import java.util.*;
public class Main {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		while (sc.hasNextDouble()) {
			double hight = sc.nextDouble();
			double degree = sc.nextDouble();
			double distance = hight/Math.tan(degree);
			System.out.println(String.format("%.2f", distance));
		}
	}
}

9. 利用海伦公式求三角形面积,了解世界科学史

参考代码

import java.math.BigDecimal;
import java.util.*;

public class Main {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		while (sc.hasNextDouble()) {
			double a = sc.nextDouble();
			double b = sc.nextDouble();
			double c = sc.nextDouble();
			if(a<=0 || b<=0 || c<=0) {
				System.out.println("Input Error!");
				continue;
			}
			double p = (a+b+c)/2;
			double S = Math.sqrt(p*(p-a)*(p-b)*(p-c));
			if(a+b>c) {
				System.out.println(String.format("%.2f", S));
			}else {
				System.out.println("Input Error!");
			}
		}
	}
}

10. 身体质量指数(BMI)测算

参考代码

import java.util.*;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        while (sc.hasNextDouble()) {
            double weight = sc.nextDouble();
            double height = sc.nextDouble();
            if (weight <= 0 || weight > 727 || height <= 0 || height > 2.72) {
                System.out.println("input out of range");
                continue;
            }
            double BMI = weight / Math.pow(height, 2);
            if (BMI < 18.5) {
                System.out.println("thin");
            } else if (BMI >= 18.5 && BMI < 24) {
                System.out.println("fit");
            } else if (BMI >= 24 && BMI < 28) {
                System.out.println("overweight");
            } else if (BMI >= 28) {
                System.out.println("fat");
            }
        }
    }
}

11. 消失的车

参考代码

import java.util.*;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        for (int i = 1000; i <= 9999; i++) {
            String card = i + "";
            String formertwo = card.substring(0, 2);
            String lattertwo = card.substring(2);
            StringBuilder fr = new StringBuilder(formertwo);
            StringBuilder lt = new StringBuilder(lattertwo);
            if (formertwo.equals(fr.reverse().toString()) && lattertwo.equals(lt.reverse().toString()) && !formertwo.equals(lattertwo)) {
                for (int j = 1; j < 100; j++) {
                    int num = j * j;
                    if (Integer.parseInt(card) == num) {
                        System.out.println("车牌号码是" + num);
                    }

                }
            }
        }
    }
}


// 偷懒版
public class Main {
    public static void main(String[] args) {

        System.out.println("车牌号码是" + 7744);
    }
}       

12. 判断回文

参考代码

import java.util.*;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String str = sc.next();
        StringBuilder re = new StringBuilder(str);
        if (str.equals(re.reverse().toString())) {
            System.out.println("yes");
        } else {
            System.out.println("no");
        }
    }
}
// 偷懒版
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        String s = scan.nextLine();
        
        // 如果翻转后相等输出 yes,否则 no
        System.out.println(new StringBuilder(s).reverse().toString().equals(s) ? "yes" : "no");
    }
}

13. 我是升旗手

输入格式:

输入包括两行。 第一行:包括一个整数n,表示班级里共有n位同学。 第二行:包含n个三位数,表示每一位同学的身高。

输出格式:

输出身高最高的同学的身高。

输入样例:

4
130 125 129 140

输出样例:

140

参考代码

import java.util.*;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int height[] = new int[n];
        for (int i = 0; i < n; i++) {
            height[i] = sc.nextInt();

        }
        int max = 0;
        for (int i = 0; i < height.length; i++) {
            if (height[i] > max) {
                max = height[i];
            }
        }
        System.out.println(max);
    }
}

14. 兔子繁殖问题

参考代码

import java.util.*;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int first = 1;
        int second = 2;
        int current = 0;
        if (n == 1) {
            current = first;
        } else if (n == 2) {
            current = second;
        } else {
            for (int i = 3; i <= n; i++) {
                current = first + second;
                first = second;
                second = current;
            }
        }
        System.out.println(current);
    }
}

15. 西安距离

参考代码

import java.util.*;

public class Main {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		int a = sc.nextInt();
		int b = sc.nextInt();
		int c = sc.nextInt();
		int d = sc.nextInt();
		System.out.println(Math.abs(c-a)+Math.abs(d-b));
	}
}

16. 构造方法与初始化块

参考代码

import java.util.*;


public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        sc.nextLine();
        Person ps[] = new Person[n];
        for (int i = 0; i < n; i++) {
            String line = sc.nextLine();
            String[] s = line.split(" ");
            Person p = new Person(s[0], Integer.parseInt(s[1]), Boolean.parseBoolean(s[2]));
            ps[i] = p;
        }
        for (int i = ps.length - 1; i >= 0; i--) {
            System.out.println(ps[i]);
        }
        Person person = new Person();
        System.out.println(person.getName() + "," + person.getAge() + "," + person.isGender() + "," + person.getNid());
        System.out.println(person);
    }
}

class Person {
    private String name;
    private int age;
    private boolean gender;
    private int id;
    private static int nid = 0;

    static {
        System.out.println("This is static initialization block");
    }

    public Person() {
        super();
        this.id = nid;
        System.out.println("This is initialization block, id is " + nid);
        System.out.println("This is constructor");
    }

    public Person(String name, int age, boolean gender) {
        super();
        this.name = name;
        this.age = age;
        this.gender = gender;
        this.id = nid;
        System.out.println("This is initialization block, id is " + nid);
        nid += 1;
    }
    //Getter 和Setter方法
    //ToString方法
    }
}

17. 打球过程

参考代码

import java.util.*;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int type = sc.nextInt();
        String res = sc.next();
        if (type == 1) {
            System.out.println("now checking in");
            System.out.println("now starting");
            System.out.println("now playing football");
            System.out.println("now ending");
            System.out.println("now annoucing result: " + res);

        } else if (type == 2) {
            System.out.println("now checking in");
            System.out.println("now starting");
            System.out.println("now playing basketball");
            System.out.println("now ending");
            System.out.println("now annoucing result: " + res);
        }
    }
}


18. 谁是最强的女汉子

参考代码

import java.util.*;

public class Main {
    public static void main(String[] args) {
       Scanner sc = new Scanner(System.in);
       int T = sc.nextInt();
       int count = 0;
       int strength = 0;
       int min_x = 0;
       for (int i = 0; i < T; i++) {
          int x = sc.nextInt();
          int y = sc.nextInt();
          if(i==0) {
             min_x = x;
          }
          if(x<min_x) {
             min_x = x;
             count=1;
             strength=y;
          }else if (x==min_x) {
             min_x = x;
             count+=1;
             strength+=y;
          }
       }
       System.out.println(count+" "+strength);
    }
}

19. 身份证排序

参考代码

import java.util.*;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        sc.nextLine();
        String ID[] = new String[n];
        for (int i = 0; i < n; i++) {
            ID[i] = sc.nextLine();
        }
        ArrayList<String> birthList = new ArrayList<String>();
        while (sc.hasNextLine()) {
            String type = sc.nextLine();
            if (type.equals("sort1")) {
                for (String id : ID) {
                    String year = id.substring(6, 10);
                    String month = id.substring(10, 12);
                    String day = id.substring(12, 14);
                    String birthformat = year + "-" + month + "-" + day;
                    birthList.add(birthformat);
                }
                Collections.sort(birthList);
                for (String b : birthList) {
                    System.out.println(b);
                }
            } else if (type.equals("sort2")) {
                Arrays.sort(ID, new Comparator<String>() {
                    @Override
                    public int compare(String o1, String o2) {
                        String birth1 = o1.substring(6, 14);
                        String birth2 = o2.substring(6, 14);
                        return birth1.compareTo(birth2);
                    }
                });
                for (String a : ID) {
                    System.out.println(a);
                }
            } else {
                System.out.println("exit");
                break;
            }


        }

    }

}

20. 找出最长的单词

参考代码

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        String input = scanner.nextLine();
        String[] words = input.split("\\s+");

        String longestword = "";
        for (String word : words) {
            if (word.length() > longestword.length()) {
                longestword = word;
            }
        }
        System.out.println(longestword);
    }
}

21. 统计一段文字中的单词个数并按单词的字母顺序排序后输出

参考代码

import java.util.*;

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

        // 读取输入直到遇到 !!!!!
        while (scanner.hasNextLine()) {
            String line = scanner.nextLine().trim();

            // 遇到结束标记
            if (line.equals("!!!!!")) {
                break;
            }
            // 忽略空行
            if (line.isEmpty()) {
                continue;
            }
            // 分割单词并加入集合
            String[] words = line.split("\\s+");
            for (String word : words) {
                if (!word.isEmpty()) {
                    wordsSet.add(word);
                }
            }
        }
        // 转换为列表并排序
        List<String> wordsList = new ArrayList<>(wordsSet);
        Collections.sort(wordsList);

        // 输出不同单词数量
        System.out.println(wordsList.size());

        // 输出单词(最多10个)
        int count = Math.min(10, wordsList.size());
        for (int i = 0; i < count; i++) {
            System.out.println(wordsList.get(i));
        }
    }
}

22. 统计一篇英文文章中出现的不重复单词的个数

参考代码

import java.util.*;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        ArrayList<String> list = new ArrayList<String>();
        String b;
        while (!"!!!!!".equals(b = sc.next().toLowerCase())) {
            list.add(b);
        }
        list = new ArrayList<String>(new HashSet<String>(list));

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

23. 打印“杨辉三角“ 品中国数学史 增民族自豪感(1)

参考代码

import java.util.*;

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int n = scanner.nextInt();
        //构建二维数组
        int[][] a = new int[n][n];
        int i, j;
        //下三角
        for (i = 0; i < n; i++) {
            for (j = 0; j <= i; j++) {
                if (j == 0 || i == j) {
                    a[i][j] = 1;
                } else {
                    a[i][j] = a[i - 1][j] + a[i - 1][j - 1];
                }
            }
        }
        //输出
        for (i = 0; i < a.length; i++) {
            for (j = 0; j <= i; j++) {
                System.out.printf("%-4d", a[i][j]);
            }
            System.out.println();
        }
    }
}

24. 找到出勤最多的人

参考代码

import java.util.*;

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        String input = scanner.nextLine();
        String[] records = input.split("\\s+");

        // 统计每个人出现的次数
        Map<String, Integer> countMap = new HashMap<>();
        for (String name : records) {
            countMap.put(name, countMap.getOrDefault(name, 0) + 1);
        }
        // 找出最大出现次数
        int maxCount = 0;
        for (int count : countMap.values()) {
            if (count > maxCount) {
                maxCount = count;
            }
        }
        // 按输入顺序收集所有出现次数等于最大次数的人
        List<String> result = new ArrayList<>();
        Set<String> added = new HashSet<>(); // 避免重复添加

        for (String name : records) {
            if (countMap.get(name) == maxCount && !added.contains(name)) {
                result.add(name);
                added.add(name);
            }
        }
        // 输出结果(空格分隔,末尾无空格)
        for (int i = 0; i < result.size(); i++) {
            if (i > 0) {
                System.out.print(" ");
            }
            System.out.print(result.get(i));
        }
    }
}

25. 01-接口-Comparable

参考代码

import java.util.*;

public class Main {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        sc.nextLine();
        PersonSortable ps[] = new PersonSortable[n];
        for (int i = 0; i < n; i++) {
            String line = sc.nextLine();
            String[] s = line.split(" ");
            PersonSortable p = new PersonSortable(s[0],Integer.parseInt(s[1]));
            ps[i]=p;
        }
        Arrays.sort(ps);
        for (PersonSortable p : ps) {
            System.out.println(p);
        }
        System.out.println(Arrays.toString(PersonSortable.class.getInterfaces()));
    }

}
class PersonSortable implements Comparable<PersonSortable>{
    private String name;
    private int age;

    public PersonSortable() {

    }

    public PersonSortable(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return name+"-"+age;
    }

    @Override
    public int compareTo(PersonSortable o) {
        if(this.name.equals(o.getName())) {
            return this.age - o.getAge();
        }else {
            return this.name.compareTo(o.getName());
        }
    }
}

26. 02-接口-Comparator

参考代码

import java.util.*;

public class Main {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        sc.nextLine();
        PersonSortable2 ps[] = new PersonSortable2[n];
        for (int i = 0; i < n; i++) {
            String line = sc.nextLine();
            String[] s = line.split(" ");
            PersonSortable2 p = new PersonSortable2(s[0], Integer.parseInt(s[1]));
            ps[i] = p;
        }
        System.out.println("NameComparator:sort");
        Arrays.sort(ps, new NameComparator());
        for (PersonSortable2 p : ps) {
            System.out.println(p);
        }
        System.out.println("AgeComparator:sort");
        Arrays.sort(ps, new AgeComparator());
        for (PersonSortable2 p : ps) {
            System.out.println(p);
        }
        System.out.println(Arrays.toString(NameComparator.class.getInterfaces()));
        System.out.println(Arrays.toString(AgeComparator.class.getInterfaces()));


    }
}

class PersonSortable2 {
    private String name;
    private int age;

    public PersonSortable2() {
    }

    public PersonSortable2(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return name + "-" + age;
    }
}

class NameComparator implements Comparator<PersonSortable2> {

    @Override
    public int compare(PersonSortable2 o1, PersonSortable2 o2) {
        return o1.getName().compareTo(o2.getName());
    }
}

class AgeComparator implements Comparator<PersonSortable2> {

    @Override
    public int compare(PersonSortable2 o1, PersonSortable2 o2) {
        return o1.getAge() - o2.getAge();
    }
}

27. 使用异常机制处理异常输入

参考代码

import java.util.*;


public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        sc.nextLine();
        int num[] = new int[n];
        for (int i = 0; i < n; i++) {
            String str = sc.nextLine();
            try {
                int j = Integer.parseInt(str);
                num[i] = j;
            } catch (NumberFormatException e) {
                i--;
                System.out.println(e);
            }
        }
        System.out.println(Arrays.toString(num));
    }
}

28. 成绩录入时的及格与不及格人数统计

参考代码

import java.util.*;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int pass = 0;
        for (int i = 0; i < n; i++) {
            int score = sc.nextInt();
            if (score < 0 || score > 100) {
                System.out.println(score + "invalid!");
                i--;
            }
            if (score >= 60 && score <= 100) {
                pass++;
            }
        }
        System.out.println(pass);
        System.out.println(n - pass);
    }
}

29. 快递计价器

现需要编写一个简易快递计价程序。具体来说:

1、抽象快递类Express,其包含一个属性int weight表示快递重量(单位为kg),一个方法getWeight()用于返回快递重量和一个抽象方法getTotal()用于计算快递运费。

2、两个类继承Express,分别是:
(a)顺路快递SLExpress:计价规则为首重(1kg)12元,每增加1kg费用加2元。
(b)地地快递DDExpress:计价规则为首重(1kg)5元,每增加1kg费用加1元。

3、Main:
接收用户通过控制台输入的N行信息,自动计算所有快递的运费总和。

参考代码

import java.util.*;


public class Main {
    public static void main(String[] args) {
          Scanner sc = new Scanner(System.in);
          int n = sc.nextInt();

          sc.nextLine();
          int total = 0;
          while (sc.hasNextLine()) {
              String line = sc.nextLine();
              String[] s = line.split(" ");
              if (s[0].equals("SL")) {
                  SLExpress sl = new SLExpress(Integer.parseInt(s[1]));
                  total += sl.getTotal();
              } else if (s[0].equals("DD")) {
                  DDExpress dd = new DDExpress(Integer.parseInt(s[1]));
                  total += dd.getTotal();
              } else {
                  break;
              }

          }
          System.out.println(total);
      }


}

abstract class Express {
    int weight;

    public Express() {
        super();
    }

    public Express(int weight) {
        super();
        this.weight = weight;
    }

    public int getWeight() {
        return weight;
    }

    public void setWeight(int weight) {
        this.weight = weight;
    }

    public int getWeight(int weight) {
        return weight;
    }

    public abstract int getTotal();
}

class SLExpress extends Express {

    public SLExpress() {
        super();
       
    }

    public SLExpress(int weight) {
        super(weight);

    }

    @Override
    public int getTotal() {

        if (weight == 1) {
            return 12;
        } else {
            return 12 + (weight - 1) * 2;
        }
    }

}

class DDExpress extends Express {

    public DDExpress() {
        super();

    }

    public DDExpress(int weight) {
        super(weight);

    }

    @Override
    public int getTotal() {
        if (weight == 1) {
            return 5;
        } else {
            return 5 + (weight - 1) * 1;
        }
    }

}

30. 答答租车系统

参考代码

import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
        Cars cars[] = {new Cars("A", 5, 0, 800),
                new Cars("B", 5, 0, 400),
                new Cars("C", 5, 0, 800),
                new Cars("D", 51, 0, 1300),
                new Cars("E", 55, 0, 1500),
                new Cars("F", 5, 0.45, 500),
                new Cars("G", 5, 2.0, 450),
                new Cars("H", 0, 3, 200),
                new Cars("I", 0, 25, 1500),
                new Cars("J", 0, 35, 2000)};
        Scanner sc = new Scanner(System.in);
        while (sc.hasNextLine()) {
            String isRent = sc.nextLine();
            if (isRent.equals("1")) {
                int count = sc.nextInt();
                int totalPerson = 0;
                double totalTon = 0.0;
                int totalSum = 0;
                sc.nextLine();
                for (int i = 0; i < count; i++) {
                    String line = sc.nextLine();
                    String[] s = line.split(" ");
                    int m = Integer.parseInt(s[0]);
                    int n = Integer.parseInt(s[1]);
                    Cars cars1 = cars[m - 1];
                    totalPerson += cars1.getPickPerson() * n;
                    totalTon += cars1.getPickTon() * n;
                    totalSum += cars1.getFee() * n;
                }
                System.out.println(totalPerson + " " + String.format("%.2f", totalTon) + " " + totalSum);

            } else {
                System.out.println("0 0.00 0");
                break;
            }
        }


    }
}

class Cars {
    private String carname;
    private int pickPerson;
    private double pickTon;
    private double fee;

    public Cars() {
    }

    public Cars(String carname, int pickPerson, double pickTon, double fee) {
        this.carname = carname;
        this.pickPerson = pickPerson;
        this.pickTon = pickTon;
        this.fee = fee;
    }

    public String getCarname() {
        return carname;
    }

    public void setCarname(String carname) {
        this.carname = carname;
    }

    public int getPickPerson() {
        return pickPerson;
    }

    public void setPickPerson(int pickPerson) {
        this.pickPerson = pickPerson;
    }

    public double getPickTon() {
        return pickTon;
    }

    public void setPickTon(double pickTon) {
        this.pickTon = pickTon;
    }

    public double getFee() {
        return fee;
    }

    public void setFee(double fee) {
        this.fee = fee;
    }

}

31. 读中国载人航天史,汇航天员数量,向航天员致敬(1)

参考代码

import java.util.*;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String name = null;
        Map<String, Integer> map = new LinkedHashMap<String, Integer>();
        while (sc.hasNext()) {
            name = sc.next();
            if (name.equals("end"))
                break;
            map.put(name, map.getOrDefault(name, 0) + 1);
        }
        for (String name1 : map.keySet()) {
            System.out.println(name1 + " " + map.get(name1));
        }
    }
}

32. 成绩异常(ScoreException)

自定义一个异常类ScoreException,继承自Exception类。有一个私有的成员变量message(异常提示信息,String类型);一个公有的无参数的构造方法,在方法中将message的值确定为“您输入的成绩异常,请核实!”;一个公有的方法show(),该方法的功能是输出message的值。

定义一个学生类Student,有一个私有成员变量score(成绩,double类型);一个带参数的公有方法setScore()用于设置学生的成绩,该方法声明可能抛出异常ScoreException,当设置的成绩为负数或超过100时,会抛出一个异常对象;一个公有方法getScore()用于获取学生的成绩。

在测试类Main中,创建一个Student类的对象zhangsan,尝试调用setScore()方法来设置他的成绩(成绩从键盘输入,double类型),然后调用getScore()方法获取到该成绩后再将其输出。因用户的输入存在不确定性,以上操作有可能捕捉到异常ScoreException,一旦捕捉到该异常,则调用show()方法输出异常提示。不管是否有异常,最终输出“程序结束”。使用try...catch...finally语句实现上述功能。

输入格式:

输入一个小数或整数。

输出格式:

可能输出:
成绩为XXX
程序结束
也可能输出:
您输入的成绩异常,请核实!
程序结束

输入样例1:

-20

输出样例1:

您输入的成绩异常,请核实!
程序结束

输入样例2:

90

输出样例2:

成绩为90.0
程序结束

参考代码

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        Student zhangsan = new Student();
        try {
            double inputScore = scanner.nextDouble();
            zhangsan.setScore(inputScore);

            // 设置成功后,调用 getScore 获取并输出
            System.out.println("成绩为" + zhangsan.getScore());

        } catch (ScoreException e) {
            e.show();
        } finally {
            System.out.println("程序结束");
        }
    }
}

// 2. 学生类 Student
class Student {
    // 私有成员变量 score
    private double score;

    // 公有方法 setScore,声明抛出 ScoreException
    public void setScore(double score) throws ScoreException {
        // 当成绩为负数或超过100时,抛出异常对象
        if (score < 0 || score > 100) {
            throw new ScoreException();
        }
        this.score = score;
    }

    // 公有方法 getScore
    public double getScore() {
        return score;
    }
}

class ScoreException extends Exception {
    // 私有成员变量 message
    private String message;

    // 公有的无参数构造方法
    public ScoreException() {
        // 确定 message 的值
        this.message = "您输入的成绩异常,请核实!";
    }

    // 公有的 show 方法,用于输出 message 的值
    public void show() {
        System.out.println(message);
    }
}

33. 超载异常(OverLoadException)

自定义一个异常类OverLoadException(超载异常),它是Exception的子类,有一个成员变量message(消息,String类型),有一个带参数的构造方法public OverLoadException(double n),使得message的值为“无法再装载重量是XXX吨的集装箱”,其中XXX为参数n的值。有一个公有的成员方法showMessage(),功能为输出message的值。

定义一个类CargoShip(货船),有成员变量actualWeight(实际装载量,double类型,初始值为0)、maxWeight(最大装载量,double类型);有公有的成员方法setMaxWeight()用于设置maxWeight的值;公有的成员方法void loading(double weight)的功能是给货船加载weight吨的集装箱。但是根据参数weight的值,该方法可能会抛出超载异常,如果装载后实际重量没有超过最大装载量,则实际装载量增加,并输出“目前共装载了XXX吨货物”,其中XXX为actualWeight的值,否则抛出一个OverLoadException异常对象。

在测试类Main中,定义一个CargoShip类的对象myship,从键盘输入一个数,用于设置其最大装载量。从键盘再输入两个数,作为两个集装箱的重量,尝试将这两个集装箱按输入时的顺序先后装上货船,该操作有可能捕捉到超载异常,一旦捕捉到该异常,则调用showMessage()方法输出异常提示。不管是否有异常,最终输出“货船将正点起航”。使用try...catch...finally语句实现上述功能。

输入格式:

第一行输入一个大于零的整数或小数,当作货船的最大装载量maxWeight。
第二行输入两个大于零的整数或小数,当作尝试装载上货船的两个集装箱的重量,中间以空格隔开。

输出格式:

根据输入的值,可能输出以下两种情况之一:
目前共装载了XXX吨货物
无法再装载重量是XXX吨的集装箱
最后输出:货船将正点起航

输入样例1:

500
200 380

输出样例1:

目前共装载了200.0吨货物
无法再装载重量是380.0吨的集装箱
货船将正点起航

输入样例2:

1000
300 500

输出样例2:

目前共装载了300.0吨货物
目前共装载了800.0吨货物
货船将正点起航

参考代码

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        CargoShip myship = new CargoShip();
        // 读取最大装载量
        double maxW = scanner.nextDouble();
        myship.setMaxWeight(maxW);
        // 读取两个集装箱的重量
        double w1 = scanner.nextDouble();
        double w2 = scanner.nextDouble();
        try {
            myship.loading(w1);
            myship.loading(w2);
        } catch (OverLoadException e) {
            e.showMessage();
        } finally {
            System.out.println("货船将正点起航");
        }
    }
}

class OverLoadException extends Exception {
    public String message;

    public OverLoadException(double n) {
        this.message = "无法再装载重量是" + n + "吨的集装箱";
    }

    public void showMessage() {
        System.out.println(message);
    }
}

class CargoShip {
    public double actualWeight = 0; //实际装载量
    public double maxWeight;//最大装载

    public void setMaxWeight(double maxWeight) {
        this.maxWeight = maxWeight;
    }

    public void loading(double weight) throws OverLoadException {
        if (actualWeight + weight > maxWeight) {
            // 如果超载,抛出异常,传入当前货物重量
            throw new OverLoadException(weight);
        } else {
            // 如果没超载,累加重量并输出
            actualWeight += weight;
            System.out.println("目前共装载了" + actualWeight + "吨货物");
        }
    }
}

34. 异常处理

从键盘输入一个整形数n,如果输入正确的话,输出10-n后的值,如果输入错误的话输出“not int”最后输出end。

输入格式:

输入一个整数n。

输出格式:

根据情况输出结果。

输入样例:

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

5

输出样例:

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

5
end

输入样例:

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

a

输出样例:

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

not int
end

import java.util.Scanner;
import java.util.InputMismatchException;

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        try {
            // 尝试读取一个整数
            int n = scanner.nextInt();
            // 如果读取成功,执行减法并输出
            System.out.println(10 - n);
        } catch (InputMismatchException e) {
            // 如果输入的不是整数(如小数或字母),捕捉异常并输出提示
            System.out.println("not int");
        } finally {
            System.out.println("end");
        }
    }
}

附加:30.天不假年

参考代码

import java.util.*;

public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int age;
        age = in.nextInt();
        Person p = new Person(age);
        age = in.nextInt();
        try {
            p.setAge(age);
            System.out.println("A");
        } catch (AgeException e) {
            System.out.println("B");
        }
    }
}

class Person {
    int age;

    public Person(int age) {
        this.age = age;
    }

    public void setAge(int age) throws AgeException {
        if (this.age <= age) {
            this.age = age;
        } else {
            throw new AgeException();
        }
    }
}

class AgeException extends Exception {
}

博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3