java-pta-代码

news/2025/12/5 19:03:17/文章来源:https://www.cnblogs.com/Syntax-StepUp/p/19313477

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 42.3 35 610 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,否则 noSystem.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>() {@Overridepublic 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;}@Overridepublic String toString() {return name+"-"+age;}@Overridepublic 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;}@Overridepublic String toString() {return name + "-" + age;}
}class NameComparator implements Comparator<PersonSortable2> {@Overridepublic int compare(PersonSortable2 o1, PersonSortable2 o2) {return o1.getName().compareTo(o2.getName());}
}class AgeComparator implements Comparator<PersonSortable2> {@Overridepublic 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);}@Overridepublic 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);}@Overridepublic 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 {// 私有成员变量 scoreprivate double score;// 公有方法 setScore,声明抛出 ScoreExceptionpublic void setScore(double score) throws ScoreException {// 当成绩为负数或超过100时,抛出异常对象if (score < 0 || score > 100) {throw new ScoreException();}this.score = score;}// 公有方法 getScorepublic double getScore() {return score;}
}class ScoreException extends Exception {// 私有成员变量 messageprivate 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 {
}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/989114.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

帝国cms升级时提示Table ***_enewsdtuserpage already exists

问题描述错误提示:Table ***_enewsdtuserpage already exists场景:在从 7.5 版本 升级到 8.0 版本 时出现该错误。 原因是数据库中已经存在 8.0 版本的表。问题原因历史遗留问题:用户之前可能安装过 8.0 测试版,但…

网站打开提示:”未检测到您服务器环境的 sqlite3 数据库扩展…“

错误描述: 网站打开时提示:未检测到您服务器环境的 sqlite3 数据库扩展,请检查您的环境!问题原因: PbootCMS 默认使用 SQLite 数据库,但服务器未启用 sqlite3 扩展。 解决方法:打开 PHP 配置文件 php.ini:路径…

chroot使用

说明 chroot一个arm环境在本地的服务器修改板子的文件很方便的。 使用 sudo chroot binary/ # 操作完成之后 退出 exit可以在debian的文件系统里面,apt其他的deb包的,制作镜像就会很方便的。 参考 https://roc-rk332…

帝国cms升级时提示Duplicate column name ecmsvpf

问题描述错误提示: Duplicate column name ecmsvpf场景:在从 7.5 版本 升级到 8.0 版本 时出现该错误。 原因是重复执行了升级程序 /e/update/upcheck.php,导致部分数据表已被更新至 8.0 表结构。问题原因重复执行升…

街头徒手健身1引体向上

想要为标准引体向上打基础,你可以在高单杠上先练三个核心动作:顶端悬停、离心下放和静态悬垂。顶端悬停 顶端悬停,指的是将身体悬停在引体向上的最高点,让下巴超过单杠。刚开始练习时,最好采用反手抓握的方式。你…

程序运行异常: Undefined constant"PAGE

程序运行异常: Undefined constant"PAGE,位: /www/wwwroot/*******/runtime/complle/8a9aa228409b7a00002e2743e8C7a.php,第287行 后台自定义表单,点击编辑字段的时候,出现整个问题了, 原因是由于php版本太高…

PBOOTCMS判断登录是否登录代码(PbootCMS登录状态判断优化方案)

在使用 {pboot:islogin} 判断用户是否登录时,发现即使本地 Cookie 已过期,{pboot:islogin} 的值仍可能为 1,导致判断不准确。 为解决此问题,可以通过检查用户的实际登录信息(如手机号)来判断登录状态是否有效。如…

2025年12月北京考公,北京考公机构最新榜,深耕公考十年 赋能青年成公——北京成公教育的教育践行之路

在青年职业发展选择愈发多元的当下,公考培训行业始终承担着为青年群体搭建职业成长桥梁的重要角色。北京成公教育咨询有限责任公司(以下简称“成公教育”)自2015年成立以来,以专业的教研实力、广泛的服务覆盖和坚定…

2025年PFA管源头厂家推荐:深耕氟塑领域 赋能高端制造——苏州江盛达以优质PFA管助力产业升级

在氟塑料管材应用日益广泛的当下,PFA管凭借优异的耐腐蚀性、耐高温性及超高纯度特性,成为高端制造领域不可或缺的关键材料。苏州江盛达自动化科技有限公司(以下简称“江盛达”)深耕该领域多年,以研发、生产、销售…

2025年12月新郑集装箱厂家:二手住人集装箱,住人集装箱,太空舱手集装箱房,附近二手集装箱,集装箱移动房源头厂家 赋能多元场景绿色发展

在全球集装箱行业向智能化、绿色化转型的浪潮中,郑州敬发钢结构工程有限公司(以下简称“郑州敬发”)凭借对钢结构与集装箱技术的深耕,构建起涵盖设计、制造、运维的全链条服务体系,为不同领域提供兼具实用性与可持…

2025年比亚迪唐更换轮胎推荐:最新轮胎评测深度报告

2025年比亚迪唐更换轮胎推荐:最新轮胎评测深度报告为解决用户在“2025年比亚迪唐更换轮胎推荐”上的选择难题,本文将基于全球主流汽车媒体(如《AutoBild》、汽车之家等)的公开评测模型与数据,从以下四大核心维度,…

完整教程:标签Labels、Scheduler:调度器、k8s污点与容忍度

pre { white-space: pre !important; word-wrap: normal !important; overflow-x: auto !important; display: block !important; font-family: "Consolas", "Monaco", "Courier New", …

第二章 硬件架构

第2章 硬件架构 本章的2.1讲述了一些与CPU相关的结构知识,本文从2.2开始复述。 2.2 集成GPU集成GPU,中的“集成”,是集成到芯片组的意思。下图展示了集成GPU的架构。可以看到,先前属于CPU的内存池现在可以被集成到…

智能体与企业转型:为什么AgenticHub是关键工具

引言:智能体在企业转型中的关键作用 在当今的商业环境中,人工智能(AI)已成为企业提高效率、降低成本和实现创新的核心工具。AgenticHub,一款创新的智能体平台,正在帮助企业在AI转型过程中加速智能体的部署和管理…

2025年比亚迪汉更换轮胎推荐:权威轮胎榜单精选推荐

2025年比亚迪汉更换轮胎推荐:权威轮胎榜单精选推荐为解决用户在“2025年比亚迪汉更换轮胎推荐”上的选择难题,本文将基于全球主流汽车媒体(如《AutoBild》、汽车之家等)的公开评测模型与数据,从以下四大核心维度,…

前端交互基石:Vue 与 Ajax 的高效协作(12.5)

在现代 Web 开发中,Vue.js 作为一款轻量、响应式的前端框架,几乎成了中小型项目的首选;而 Ajax(Asynchronous JavaScript and XML) 则是实现前后端异步通信的核心技术。二者结合,构成了绝大多数单页应用(SPA)的…

2025年中国铝氧化着色定制品牌五大推荐:看哪家技术实力强?

TOP1 推荐:佛山市南海区海光铝氧化有限公司 推荐指数:★★★★★ 口碑评分:国内专业的铝氧化着色定制品牌 专业能力:作为深耕铝氧化领域35年以上的资深企业,佛山市南海区海光铝氧化有限公司以质量第一,信誉至上为…

ZR2024 数据结构

started in 2025.12.5 15:55。 CF1762F Good Pairs给定一个长度为 \(n\) 的数组 \(a\),问有多少对 \((l,r)\) 满足存在一个首尾是 \(l,r\) 的单增下标子序列满足相邻对应数之差绝对值不超过 \(k\)。 \(n \leq 5 \time…

2025年奔驰E级更换轮胎推荐:专业轮胎选择官方攻略

2025年奔驰E级更换轮胎推荐:专业轮胎选择官方攻略在豪华行政轿车细分市场中,奔驰E级始终以精密的德系底盘调校、卓越的乘坐质感与智能化驾驶体验稳居主流阵营。进入2025年,伴随轮胎更换周期的到来,“2025年奔驰E级…

2025年二次元测量仪工厂有哪些?主要有哪些优质产品?

二次元测量仪工厂的产品涵盖多个领域,主要是为满足高精度测量的需求。比如,光学二次元测量仪企业提供的设备在精密检测上具有显著优势,尤其适用于小型和复杂零件的质量控制。同时,台面导轨二次元测量仪优质厂家的产…