题目列表

  • 7-1 一个整数各个位上的最大数字
  • 7-2 十进制转二进制
  • 7-3 判断回文
  • 7-4 学投资
  • 7-5 打印所有的水仙花数
  • ​7-6 逆序输出整数
  • 7-7 1!+2!+……+N!
  • 7-8 完数
  • 7-9 n个a数字求和
  • 7-10 数字统计
  • 7-11 尼科彻斯定理
  • 7-12 复数类的定义
  • 7-13 MyDate类
  • 7-14 Person类-静态变量
  • 7-15 卡片邻居游戏
  • 7-16 Battery Charge
  • 7-17 N个数的排序与查
  • 7-18 整数数组比较
  • 7-19 多数组排序
  • 7-20 两队PK
  • 7-21 数组元素的删除
  • 7-22 sdut-array1-1 RDMP音乐播放器(II)(一维数组)
  • 7-23 重复数据问题
  • 7-24 公司季度销售额以及年销售额统计
  • 7-25 解析二维数组
  • 7-26 矩阵类
  • 7-27 sdut-array1-2 RDMP音乐播放器(III)(一维数组)
  • 7-28 sdut-array2-2-局部峰值
  • 7-29 sdut-array2-3 二维方阵变变变
  • 7-30 sdut-array2-4 打印“杨辉三角“ 品中国数学史 增民族自豪感(1)
  • 7-31 sdut-array2-5 打印“杨辉三角“ 品中国数学史 增民族自豪感(2)
  • 7-32 Shape类-2
  • 7-33 学生、大学生、研究生类-2
  • 7-34 打球过程
  • 7-35 jmu-Java-04面向对象进阶-03-接口-自定义接口ArrayIntegerStack
  • 7-36 USB接口的定义
  • 7-37 职工排序题
  • 7-38 接口--四则计算器
  • 7-39 sdut-oop-7 答答租车系统(类的继承与多态 面向对象综合练习)
  • 7-40 镜像字符串
  • 7-41 字符串
  • 7-42 各类字符数
  • 7-43 数据类型判断
  • 7-44 打印双休日
  • 7-45 比较日期
  • 7-46 我也会加密
  • 7-47 将一整个正整数的所有位重新排序,组成一个最大数
  • 7-48 jmu-Java-02基本语法-03-身份证排序
  • 7-49 单词在句子中的位置
  • 7-50 学生Map
  • 7-51 sdust-Java-字符串集合求并集
  • 7-52 手机按价格排序、查找
  • 7-53 jmu-Java-05集合-4-倒排索引
  • 7-54 测试抛出异常
  • 7-55 较为复杂情况下的求和
  • 7-56 InputMismatchException异常
  • 7-57 设计一个Tiangle异常类
  • 7-58 自定义异常:超载异常(OverLoadException)

7-1 一个整数各个位上的最大数字

编写一个类的方法,其输入参数为一个整数,输出为该整数各个位上的最大数字。

输入格式:
输入一个整数N

输出格式:
输出该整数N各个位上的最大数字

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

59274

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

9

答案:

import java.util.*;public class Main{public static void main(String []args){Scanner s = new Scanner(System.in);int N = s.nextInt();int max =  0,a = 0;while(N!=0) {a = N % 10;N /= 10;if(a>max) max = a;}System.out.println(max);}
}

7-2 十进制转二进制

编写代码,要求:输入参数是一个正整数,输出该整数所对应的二进制数对应的字符串。

输入格式:
正整数

输出格式:
输入的正整数对应的二进制字符串“1001”

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

9

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

1001

答案:


7-3 判断回文

编码实现:输入一个字符串,判断该字符串是否是回文(回文是指将该字符串含有的字符逆序排列后得到的字符串和原字符串相同的字符串)如果是回文,则输出“Yes”;否则输出“No”。

输入格式:
判定是否是回文的字符串

输出格式:
“Yes”或者“No”

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

TooooT

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

Yes

答案:

import java.util.*;public class Main {public static void main(String[] args) {Scanner s = new Scanner(System.in);String str = s.nextLine();String revers = "";for (int i = str.length()-1; i >= 0; i--) {revers += str.charAt(i);}if (str.equals(revers)) {System.out.println("Yes");} elseSystem.out.println("No");}
}

7-4 学投资

小白学习了一些复利投资知识,想比较一下复利能多赚多少钱(所谓复利投资,是指每年投资的本金是上一年的本金加收益。而非复利投资是指每年投资金额不包含上一年的收益,即固定投资额)。假设他每年固定投资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 s = new Scanner(System.in);int m = s.nextInt();double p = s.nextDouble();int n = s.nextInt();long a = Math.round(m * Math.pow(1 + p, n));long b = Math.round(m + m * p * n);System.out.print(a + " ");System.out.print(b + " ");System.out.println(a - b);}
}

7-5 打印所有的水仙花数

编写程序打印出所有的水仙花数。所谓"水仙花数"是指一个三位数,其各位数字立方和等于该本身。例如:153是一个水仙花数,因为153=13+53+3^3。 输出的数之间用“,”(英文半角的逗号)分割。

输入格式:

输出格式:

153,370,371,407

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


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

153,370,371,407

答案:

import java.util.*;public class Main {public static void main(String[] args) {Scanner s = new Scanner(System.in);int flag = 0;for (int n = 100; n < 999; n++) {int a = n % 10, b = (n / 10) % 10, c = (n / 100) % 10;if (Math.pow(a, 3) + Math.pow(b, 3) + Math.pow(c, 3) == n) {if (flag == 0) {System.out.print(n);flag = 1;} elseSystem.out.print("," + n);}}}
}

​7-6 逆序输出整数

编写程序将整数逆序输出。如输入为9876输出为6789
Main函数中读入n个整数,输出n个整数的逆序数

输入格式:
整数个数n
n个整数

输出格式:
n个整数的逆序数

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

3
1234
2323
1112

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

4321
3232
2111

答案:

import java.util.*;public class Main {public static void main(String[] args) {Scanner s = new Scanner(System.in);int n = s.nextInt();for(int i = 0;i<n;i++) {String s1 = s.next();StringBuilder s2 = new StringBuilder(s1);System.out.println(s2.reverse());}  }
}

7-7 1!+2!+……+N!

给定一个整数N,编写程序求1!+2!+……+N!(0<N<100)

输入格式:
输入一个整数N

输出格式:
输出1!+2!+……+N!

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

6

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

873

答案:

import java.util.*;public class Main {public static void main(String[] args) {Scanner s = new Scanner(System.in);int n = s.nextInt();int result = 0;while(n!=0) {result += JC(n);n--;}System.out.println(result);}public static int JC(int n) {if (n == 0)return 1;elsereturn n * JC(n - 1);}
}

7-8 完数

一个数如果恰好等于它的因子之和,这个数就称为"完数"。 例如,6的因子为1、2、3,而6=1+2+3,因此6是"完数"。 编程序找出N之内的所有完数。

输入格式:
整数N

输出格式:
N之内的所有完数,每个完数之间用逗号(英文半角)分隔开。注意:1不作为完数

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

30

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

6,28

答案:

import java.util.*;public class Main {public static void main(String[] args) {Scanner s = new Scanner(System.in);int n = s.nextInt();int flag = 0;for (int i = 1; i < n; i++) {if (Wanshu(i)) {if (flag == 0) {System.out.print(i);flag = 1;} elseSystem.out.print("," + i);}}}public static boolean Wanshu(int a) {int r = 0;if (a == 0)return false;for (int i = 1; i < a; i++) {if (a % i == 0) {r += i;}}if (r == a)return true;elsereturn false;}
}

7-9 n个a数字求和

求Sn=a+aa+aaa+…+aa…aaa(有n个a)之值,其中a是一个数字(1<=a<=9)。例如:2+22+222+2222+22222(a=2,n=5),a和n由键盘输入。

输入格式:
a,n(说明:a是出现在各个数字每一位的数字,n是最大数的位数)

输出格式:
Sn=a+aa+aaa+…+aa…aaa的值

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

2 3

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

246

答案:

import java.util.*;
public class Main {public static void main(String[] args) {Scanner s = new Scanner(System.in);int a = s.nextInt();int n = s.nextInt();int r = 0, sum = 0;for (int i = 0; i < n; i++) {sum = sum * 10 + a;// System.out.println(sum);r += sum;}System.out.println(r);}
}

7-10 数字统计

输入一个长整型的数,统计其中0、1、2、3、4、5、6、7、8、9各个数字的个数,并将结果合成一个整数。(前面的0不输出)

输入格式:
长整型数

输出格式:
合成后的整数

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

234353632

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

24111000

答案:

import java.util.Scanner;
public class Main {public static void main(String[] args) {Scanner s= new Scanner(System.in);String a = s.next();int[] b = new int[10];for(int i = 0; i < 10; i++)b[i] = 0;for(int i = 0; i < a.length(); i++){int n = a.charAt(i) - '0';b[n]++;}int k=0;for(int i=0;i<10;i++) {if(b[i]!=0)k=1;if(k==1)System.out.print(b[i]);}}
}

7-11 尼科彻斯定理

验证尼科彻斯定理,即:任何一个正整数 N 的立方都可以写成 N 个连续奇数之和。(首个奇数是:N*N-N+1)

输入格式:
任一正整数N。

输出格式:
该数的立方分解为一串连续奇数的和。

输入样例:

13

输出样例:

13*13*13=2197=157+159+161+163+165+167+169+171+173+175+177+179+181

答案:

import java.util.*;public class Main {public static void main(String[] args) {Scanner s = new Scanner(System.in);int n = s.nextInt();System.out.print(n + "*" + n + "*" + n + "=" + n * n * n + "=");int a = n * n - n + 1;System.out.print(a);for (int i = 1; i < n; i++) {a += 2;System.out.print("+" + a);}}
}

7-12 复数类的定义

编写一个复数类,可以进行复数加法和减法运算。编写一个包含main方法的类测试该复数类。要求该复数类至少包含一个无参的构造方法和一个带参的构造方法;数据成员包括复数的实部和虚部,为double类型;包括两个方法,分别实现复数的加法和减法运算。测试代码如下:

    public static void main(String [] args){Complex a=new Complex();Complex b=new Complex();Scanner in=new Scanner(System.in);a.setRealPart(in.nextDouble());a.setImaginaryPart(in.nextDouble());b.setRealPart(in.nextDouble());b.setImaginaryPart(in.nextDouble());System.out.println(a);System.out.println(b);System.out.println(a.add(b));System.out.println(a.sub(b));
}

输入格式:
输入两个复数。输入为两行,每一行为一个复数的实部和虚部,用空格隔开。

输出格式:
输出复数加法和减法结果。输出为4行,第一行和第二行输出两个复数,第三行为两个复数的加法运算结果,第四行为减法运算结果。

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

1 2
3 4
-1 2
1 2

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

1.0+2.0i
3.0+4.0i
4.0+6.0i
-2.0-2.0i
-1.0+2.0i
1.0+2.0i
4.0i
-2.0

答案:

import java.util.*;public class Main {public static void main(String[] args) {Complex a = new Complex();Complex b = new Complex();Scanner in = new Scanner(System.in);a.setRealPart(in.nextDouble());a.setImaginaryPart(in.nextDouble());b.setRealPart(in.nextDouble());b.setImaginaryPart(in.nextDouble());System.out.println(a);System.out.println(b);System.out.println(a.add(b));System.out.println(a.sub(b));}
}class Complex {double real;double image;public Complex() {}public Complex(double r, double i) {this.real = r;this.image = i;}public void setRealPart(double r) {this.real = r;}public void setImaginaryPart(double i) {this.image = i;}public Complex sub(Complex b) {Complex c = new Complex();c.real = this.real - b.real;c.image = this.image - b.image;return c;}public Complex add(Complex b) {Complex c = new Complex();c.real = this.real + b.real;c.image = this.image + b.image;return c;}public String toString() {if (real == 0)return image + "i";if (image == 0)return real + "";if (image > 0)return real + "+" + image + "i";return real + "" + image + "i";}}

7-13 MyDate类

构造日期类MyDate类,包含年月日,提供相应的get和set函数,提供void print()函数打印日期,提供int compare(MyDate d)测试当前对象和参数对象d的早晚,如果早则返回-1,晚则返回1,相等则返回0
在main函数中,读入两个日期对象,输出第一个日期对象的信息,输出两个对象的比较结果

输入格式:
两个日期对象,第一个为当前日期对象的年月日,第二个为待比较日期对象的年月日

输出格式:
当前日期对象的信息,当前对象和待比较日期对象的比较结果

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

2008 6 12 2009 6 22

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

6/12/2008 -1

答案:

import java.util.Scanner;public class Main {public static void main(String[] argc){Scanner scan = new Scanner(System.in);int Year = scan.nextInt();int Month = scan.nextInt();int Day = scan.nextInt();int AnotherYear = scan.nextInt();int AnotherMonth = scan.nextInt();int AnotherDay = scan.nextInt();scan.close();MyDate firstDay = new MyDate(Year, Month, Day);MyDate secondDay = new MyDate(AnotherYear, AnotherMonth, AnotherDay);firstDay.print();System.out.print(firstDay.compare(secondDay));}
}
class MyDate {private int year;private int month;private int day;public MyDate(int year, int month, int day){this.year = year;this.month = month;this.day = day;}public void setYear(int y){year = y;}public void setMonth(int m){month = m;}public void setDay(int d){day = d;}public int getYear(){return year;}public int getMonth(){return month;}public int getDay(){return day;}public void print(){System.out.print(month + "/" + day + "/" + year + " ");}public int compare(MyDate d){if (d.year > this.year){return -1;}else if (d.year == this.year){if (d.month > this.month){return -1;}else if (d.month == this.month){if (d.day > this.day){return -1;}else if (d.day == this.day){return 0;}}}return 1;}
}

7-14 Person类-静态变量

在Person类的基础上,添加一个静态变量avgAge表示所有Person对象的平均年龄(整数),提供方法getAvgAge能够读取该静态变量。
main函数中,构造三个Person类的对象,读入他们的信息,并输出他们的平均年龄

输入格式:
多个用户信息

输出格式:
平均年龄

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

a male 23
b female 21
c male 22

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

22

答案:

import java.util.*;public class Main{public static void main(String[] args) {Scanner scan = new Scanner(System.in); Person p = new Person();for(int i = 0;i<3;i++){String name = scan.next();      String sex = scan.next();      int age = scan.nextInt();p = new Person(name,sex,age);}System.out.println(p.getAvgAge());}
}class Person {private String name;private String sex;private int age;static int avgAge = 0;public Person(){name = null;sex = null;age = 0;}public Person(String n, String s,int a){name = n;sex = s;age = a;avgAge += age;}public int getAvgAge(){return avgAge/3;}public void setName(String n){name = n;}public void setSex(String s){sex = s;}public void setAge(int a){age = a;}
}

7-15 卡片邻居游戏

有个游戏叫卡片邻居游戏,它使用多张正方形的卡片,每张卡片在上下左右四边上有数字,可以顺时针旋转,如下图所示。

卡片在游戏板上被放成一排,相邻两张卡片的邻边应当具有相同的数字,不断有新的卡片需要放置到游戏板上,放置的位置应当满足相临边数字相同的要求(亦可放在头部和尾部)。下图展示了游戏板上的一组卡片排列和新增一张卡片后的游戏板



完成类NumberCard,包含构造函数和方法 rotate 和 getLeft,getRight,分别表示顺时针旋转卡片,返回左侧数字,返回右侧数字

完成类CardGame表示游戏版,包含方法int getIndexForFit(NameCard),boolean insertCard(NameCard),print()
其中getIndexForFit返回通过若干旋转能将卡片插入到游戏板中的最靠前的位置,头部位置为0. insertCard将卡片通过最少的旋转插入到游戏板,按旋转完成的方向插入getIndexForFit返回的位置,返回插入成功与否。print函数按顺序输出每个卡片,每个卡片按照上右下左的顺序输出各个边上的数字。(注:应当选择适当的结构存储游戏板中的卡片)

输入格式:
插入新的卡片的个数
每个新插入的新卡片,按上右下左顺序

输出格式:
依次输出游戏板上各个卡片,按上右下左的顺序

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

3
1 2 3 4
6 4 3 3
4 3 7 4

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

4 3 7 4 6 4 3 3 1 2 3 4

答案:

import java.util.Scanner;public class Main {public static void main(String[] args) {Scanner input = new Scanner(System.in);int n=input.nextInt();int[] a=new int[4];CardGame cardgame=new CardGame();cardgame.card[0].nextmark=1;for(int i=0;i<n;i++){for(int j=0;j<4;j++){a[j]=input.nextInt();}NumberCard c=new NumberCard(a);c.mark=NumberCard.num++;cardgame.insertCard(c);}cardgame.print();}
}class NumberCard {public int[] number;public int mark;public int nextmark;public int left, right;public static int num = 2;public NumberCard(int[] a) {number = new int[4];for (int i = 0; i < 4; i++) {number[i] = a[i];}left = 0;right = 0;mark = 0;nextmark = 0;}public NumberCard() {number=new int[4];left = 0;right = 0;mark = 0;nextmark = 0;}public int getLeft() {return number[3];}public int getRight() {return number[1];}public void rotate() {for (int i = 0; i < 4; i++) {number[i] = number[(i - 1 + 4) % 4];}}
}class CardGame {public NumberCard[] card;public CardGame() {card=new NumberCard[100];for(int i=0;i<100;i++){card[i]=new NumberCard();}card[0].nextmark = 1;card[1].mark=1;}public int getIndexForFit(NumberCard c) {for (int i = 0; i < 4; i++){for (int j = 0; j != 1;) {boolean left = false, right = false;NumberCard a = card[j], b = card[card[j].nextmark];if (a.mark == 0 || a.number[1] == c.number[3])left = true;if (b.mark == 1 || b.number[3] == c.number[1])right = true;if (left==true && right==true) {return j;}j = card[j].nextmark;}c.rotate();}return -1;}public boolean insertCard(NumberCard c) {int x = getIndexForFit(c);if (x == -1)return false;c.nextmark = card[x].nextmark;card[x].nextmark = c.mark;card[c.mark]=c;return true;}public void print() {int x = card[0].nextmark;boolean flag=false;while (x != 1) {for (int i = 0; i < 4; i++) {if(flag==true)System.out.print(" "+card[x].number[i]);elseSystem.out.print(card[x].number[i]);flag=true;}x=card[x].nextmark;}}
}

7-16 Battery Charge

电动汽车的电池必须周期性地进行充电,每次充电若干小时,充电过程不能被中断。充电费用基于充电的起止时间决定,费用表列出了一天内各个小时(0-23)的充电费率。每天使用的充电费率表相同,每小时费率是正整数。一个充电费率表示例如下图所示

类BatteryCharger使用费率表来决定最经济的充电方式。该类包含如下两个公有方法:

int getChargeCost(int startHour, int chargeTime) 该方法返回从开始时间经过一定的充电时长的全部充电费用。

int getChargeStartTime(int chargeTime),该函数返回给定充电时长后能使充电费用最小的起始时间。如果存在多个可能的起始时间能产生最少的费用,返回较早(较小)的一个时间。

请写出BatteryCharge类。

在main函数中首先读入24个整数代表每个小时的费用,而后调用getChargeCost,读入两个参数startHour和chargeTime,输出总的费用;而后调用getChargeStartTime,读入充电时间chargeTime,输出费用最少的起始时间。

输入格式:
每小时费用
开始时间和充电时间
充电时间

输出格式:
总的费用
最小费用的起始时间

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

50 60 160 60 80 100 100 120 150 150 150 200 40 240 220 220 200 200 180 180 140 100 80 60
0 2
7

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

110
22

答案:

import java.util.*;class BatteryCharger{int [] t;public BatteryCharger(int[] t) {this.t = t;}int getChargeCost(int startHour, int chargeTime) {int sum = 0;for(int i = startHour; i < startHour + chargeTime; i++) {sum += t[i%24];}return sum;}int getChargeStartTime(int chargeTime) {int mincost = 99999;int starttime = 0;for(int i = 0; i < 24; i++) {int sumcost = 0;for(int j = i; j < i+chargeTime; j++) {sumcost += t[j%24];}if(sumcost < mincost) {mincost = sumcost;starttime = i;}}return starttime;}}public class Main {public static void main(String [] args){Scanner scan = new Scanner(System.in);int t[] = new int[24];//用数组存放24小时的充电费率for(int i = 0; i < 24; i++) {t[i] = scan.nextInt();}BatteryCharger s = new BatteryCharger(t);System.out.println(s.getChargeCost(scan.nextInt(), scan.nextInt()));System.out.println(s.getChargeStartTime(scan.nextInt()));}
}

7-17 N个数的排序与查

从键盘输入N个整数,并输出指定的某个整数在这N个整数中的按照由小到大的顺序排列的位次(最小的位次是1,最大的位次是N,指定的整数如果不在这N个数中,则其位次是-1)

输入格式:
整数个数,指定的整数值

输出格式:
指定的整数的位次

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

3
12 4 7
4

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

1

答案:

import java.util.*;public class Main {public static void main(String [] args){Scanner scan = new Scanner(System.in);int num = scan.nextInt();int flag = 0;int arr[] = new int [num];int arr2[] = new int [num];for(int i = 0; i < num; i++) {arr[i] = scan.nextInt();}System.arraycopy(arr, 0, arr2, 0, num);Arrays.sort(arr2);int x = scan.nextInt();for(int i = 0; i < num; i++) {if(arr2[i]==x) {System.out.printf("%d",i+1);flag = 1;}}if(flag == 0) {System.out.printf("%d",-1);}   }
}

7-18 整数数组比较

给定两个整型数组A和B,将A的元素复制到B中,使得两个数组完全相同。再将B数组从小到大排列,将两数组的同一位置上对应的元素进行比较,统计出A中大于B的元素个数,等于B中元素的个数,小于B中的元素的个数。
提示:可用Arrays.sort排序

输入格式:
数组A的个数
数组A元素

输出格式:
A大于B的个数
A等于B的个数
A小于B的个数

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

10
23 1 32 87 65 12 21 9 76 45

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

4
1
5

答案:

import java.util.*;public class Main {public static void main(String [] args){Scanner scan = new Scanner(System.in);int BigNum = 0;int EqualNum = 0;int SmallNum = 0;int num = scan.nextInt();int arr1[] = new int [num];int arr2[] = new int [num];for(int i = 0; i < num; i++) {arr1[i] = scan.nextInt();//  arr1[i] = arr1[i];}System.arraycopy(arr1, 0, arr2, 0, num);Arrays.sort(arr2);for(int i = 0; i < num; i++) {if(arr1[i] > arr2[i]) {BigNum++;}else if(arr1[i] == arr2[i]) {EqualNum++;}else if(arr1[i] < arr2[i]) {SmallNum++;}}System.out.println(BigNum);System.out.println(EqualNum);System.out.println(SmallNum);}
}

7-19 多数组排序

3个整数数组进行整体排序,根据输入的三个数组的元素,输出排序后的结果(从大到小)

输入格式:
第1个数组的长度

第1个数组的各个元素

第2个数组的长度

第2个数组的各个元素

第3个数组的长度

第3个数组的各个元素

输出格式:
所有数组的整体排序

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

3
79 80 61
3
88 66 77
2
23 90

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

90 88 80 79 77 66 61 23

答案:

import java.util.Arrays;
import java.util.Scanner;
public class Main {public static void main(String[] args) {// TODO Auto-generated method stubScanner sc = new Scanner(System.in);int M = sc.nextInt();int[] cns1= new int[M];for(int i=0; i<M; i++) {cns1[i]=sc.nextInt();}int N = sc.nextInt();int[] cns2= new int[N];for(int i=0; i<N; i++) {cns2[i]=sc.nextInt();}int P = sc.nextInt();int[] cns3= new int[P];for(int i=0; i<P; i++) {cns3[i]=sc.nextInt();}int cns[]=new int[M+N+P];for(int i=0;i<M+N+P;i++) {if(i<M)cns[i]=cns1[i];else if(i<M+N)cns[i]=cns2[i-M];elsecns[i]=cns3[i-M-N];}Arrays.sort(cns);for(int i=cns.length-1;i>=0;i--) {System.out.print(cns[i]);if(i!=0)System.out.print(" ");}}
}

7-20 两队PK

A、B两队进行比赛,每队各有多名队员及其分数(分数不重复),使用A、B队所有队员得分的TOP 3来判断两队输赢,在TOP 3中拥有更多人数的队获胜。写程序实现该过程。

输入格式:
A队人数

A队每人得分

B队人数

B队每人得分

输出格式:
前三甲分数

赢的队

输入样例:

5
22 33 44 55 11
4
12 32 42 52

输出样例:

55 52 44
A

答案:

import java.util.Arrays;
import java.util.Scanner;
public class Main {public static void main(String[] args) {// TODO Auto-generated method stubScanner sc = new Scanner(System.in);int M = sc.nextInt();int[] cns1= new int[M];int top[]=new int[6];for(int i=0; i<M; i++) {cns1[i]=sc.nextInt();}Arrays.sort(cns1);int N = sc.nextInt();int[] cns2= new int[N];for(int i=0; i<N; i++) {cns2[i]=sc.nextInt();}Arrays.sort(cns2);for(int i=0;i<6;i++) {if(i<3)top[i]=cns1[i+M-3];elsetop[i]=cns2[i+N-6];}Arrays.sort(top);int charA=0;int charB=0;for(int i=2;i>=0;i--) {if(Arrays.binarySearch(cns1, top[i+3])>=0)charA++;if(Arrays.binarySearch(cns2, top[i+3])>=0)charB++;if(i==0)System.out.println(top[i+3]);elseSystem.out.print(top[i+3]+" ");}if(charA>charB)System.out.println("A");elseSystem.out.println("B");}
}

7-21 数组元素的删除

第一行包括一个整数n(1<=n<=100),表示数组元素的个数。
第二行输入n个数组元素,均为整数,用空格隔开。
第三行输入一个数k(1<=k<=100),表示要进行k次删除。
接下来k行,每行一个数x,表示要删除第x个元素。

输出格式:
输出经过k次删除后的数组,每两个元素之间用空格隔开。

输入样例:

10
1 2 3 4 5 6 7 8 9 10
4
3
2
4
6

输出样例:

1 4 5 7 8 10

答案:

import java.util.LinkedList;
import java.util.Scanner;public class Main {public static void main(String[] args) {Scanner sc = new Scanner(System.in);LinkedList<Integer> list = new LinkedList<Integer>();int n = sc.nextInt();for (int i = 0; i < n; i++) {list.add(sc.nextInt());}int k = sc.nextInt();for (int i = 0; i < k; i++) {int index = sc.nextInt();list.remove(index - 1);}sc.close();for (int i = 0; i < list.size(); i++) {System.out.print(list.get(i));if (i < list.size() - 1) {System.out.print(" ");}}}
}

7-22 sdut-array1-1 RDMP音乐播放器(II)(一维数组)

注意: 这是在使用数组的情况下完成的。RDMP音乐播放器将存储5首歌曲,它们的名称将永远是“A”,“B”,“C”,“D”和“E”。RDMP有3个按钮,用户可以按下这些按钮来重新排列播放列表并播放歌曲。
最初,RDMP播放列表是“A, B, C, D, E”。3个控制按钮做以下工作:按钮1:将播放列表的第一首歌曲移动到播放列表的末尾。例如:“A, B, C, D, E”会变成“B, C, D, E, A”。按钮2:将播放列表的最后一首歌移动到播放列表的开始。例如,“A, B, C, D, E”会变成“E, A, B, C, D”。按钮3:交换播放列表的前两首歌。例如,“A, B, C, D, E”会变成“B, A, C, D, E”。你需要编写一个程序来模拟一个可以按下n次按钮的RD音乐播放器。(n>0)

输入格式:

输入有多行。
首行是数值n,表示后续要按下按钮的次数。
后续有n行。均为1到3之间的数字,代表要采取的行动。

输出格式:

输出最终播放列表的正确顺序。
歌曲名称中间用逗号作分隔。最后一首歌名称之后没有逗号。

输入样例1:

1
1

输出样例1:

B,C,D,E,A

输入样例2:

1
2

输出样例2:

E,A,B,C,D

输入样例3:

1
3

输出样例3:

B,A,C,D,E

输入样例4:

6
1
2
3
3
2
1

输出样例4:

A,B,C,D,E

答案:


7-23 重复数据问题

在一大堆数据中找出重复的是一件经常要做的事情。现在要处理许多整数,在这些整数中,可能存在重复的数据。
你要写一个程序来做这件事情,读入数据,检查是否有重复的数据。如果有,输出“yes”这三个字母;如果没有,则输出“no”。

输入格式:
程序会读到n个整数的字符串【1<=n<=10000】,以空格分开,这些整数的范围是[1,10000]。

输出格式:
如果这些整数中存在重复的,就输出:
yes

否则,就输出:
no

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

1 2 3 1 4

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

yes

答案:


7-24 公司季度销售额以及年销售额统计

年底了,某公司要做销售统计,请输入各月份的销售额(单位:万元),请分别统计每季度的以及全年度的公司销售总额。
要求:
1.用一个四行3列数组记录销售额

2.在Main类中写一个方法统计并输出季度以及全年度的销售总额,并输出。方法声明定义为:

public static void showTotal(int [][]sale)

3.在main方法中顶一个二维数组并通过键盘输入各月份的销售总额,然后调用showTotal方法,输出统计结果。

输入格式:
输入在一行中给出12个月份的销售额,中间用空格隔开。

输出格式:
每一行分别输出各季度的销售额总和,最后一行输出年度销售额。

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

22 33 44 33 44 66 77 45 64 43 34 23 45

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

1季度的销售额为:99
2季度的销售额为:143
3季度的销售额为:186
4季度的销售额为:100
全年销售额为:528

答案:

import java.util.Scanner;public class Main{public static void main(String[] args) {Scanner cin = new Scanner(System.in);int a[][] = new int [10][10];//防溢出for(int i = 1; i <= 4; i++) {for(int j = 1; j <= 3; j++) {a[i][j] = cin.nextInt();}}showTotal(a);  }//方法 统计并输出季度及全年的销售总额public static void showTotal(int [][]sale) {int sum = 0;for(int i = 1; i <= 4; i++) {int s = 0;for(int j = 1; j <= 3; j++) {s += sale[i][j];} System.out.println(i+"季度的销售额为:"+s);sum += s;  }System.out.println("全年销售额为:"+sum);}
}

7-25 解析二维数组

读入一个字符串,该字符串表示一个整型二维数组d,数组中的元素通过解析字符串参数获得。例如,字符串参数:“1,2;3,4,5;6,7,8”,对应的数组为:
d[0,0] = 1 d[0,1] = 2
d[1,0] = 3 d[1,1] = 4 d[1,2] = 5
d[2,0] = 6 d[2,1] = 7 d[2,2] = 8
打印这个数组各元素的内容

输入格式:
字符串

输出格式:
二维数组各元素

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

1,2;3,4,5;6,7,8

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

d[0,0] = 1 d[0,1] = 2
d[1,0] = 3 d[1,1] = 4 d[1,2] = 5
d[2,0] = 6 d[2,1] = 7 d[2,2] = 8

答案:

import java.util.Scanner;
public class Main{public static void main(String[] args) {Scanner sc = new Scanner(System.in);String str;str = sc.next();//读入字符串int i = 0,j = 0;if(str.length()!=0) {System.out.print("d[" + i + "," + j + "] = ");}for(int k = 0; k < str.length(); k++) {if(str.charAt(k)==',') {j++;System.out.print(" d[" + i + "," + j + "] = ");}else if(str.charAt(k)==';') {i++;j = 0;System.out.print("\nd[" + i + "," + j + "] = ");}else {System.out.print(str.charAt(k));}}}
}

7-26 矩阵类

利用二维数组(int[])实现一个矩阵类:Matrix。要求提供以下方法:(1)set(int row, int col, int value):将第row行第col列的元素赋值为value;(2)get(int row,int col):取第row行第col列的元素;(3)width():返回矩阵的列数;(4)height():返回矩阵的行数;(5)Matrix add(Matrix b):返回当前矩阵与矩阵b相加后的矩阵;(6)Matrix multiply(Matrix b):返回当前矩阵与矩阵b相乘后的矩阵。(7)Matrix transpose():返回当前矩阵的转置矩阵;(8)toString():以行和列的形式打印出当前矩阵。

输入格式:
矩阵的行列数
矩阵的数据
设置矩阵值的行、列和值
获取矩阵值的行、列
待相加矩阵的行列数
待相加矩阵的值
待相乘矩阵的行列数
待相乘矩阵的值

输出格式:
矩阵的行、列数
设置矩阵值后的矩阵
某行某列的矩阵值
矩阵相加结果
矩阵相乘结果
矩阵转置结果

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

3 3
1 2 3
4 5 6
7 8 9
2 3 8
1 3
3 3
1 2 3
4 5 6
7 8 9
3 2
1 2
1 2
1 2

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

row:3 column:3
after set value:
1 2 3
4 5 8
7 8 9
value on (1,3):3
after add:
2 4 6
8 10 14
14 16 18
after multiply:
6 12
17 34
24 48
after transpose:
1 4 7
2 5 8
3 8 9

答案:

import java.text.DecimalFormat;
import java.util.*;class Matrix {private int row;private int col;// private double value;double[][] Data;public Matrix(int row, int col, double[][] Data) {this.row = row;this.col = col;// this.value = value;this.Data = Data;}public void setMatrix(int row, int col, double value) {this.Data[row - 1][col - 1] = value;}public double getMatrix(int row, int col) {return Data[row - 1][col - 1];}public int width() {return row;}public int height() {return col;}public Matrix add(Matrix b) {if (this.width() != b.width() && this.height() != b.height()) {return null;}double add[][] = new double[this.row][this.col];for (int i = 0; i < col; i++) {for (int j = 0; j < row; j++) {add[i][j] = this.Data[i][j] + b.Data[i][j];}}Matrix another = new Matrix(this.col, this.row, add);System.out.println("after add:");return another;}public Matrix multiply(Matrix b) {if (this.col != b.row) {return null;}double mul[][] = new double[this.row][b.col];double temp = 0;for (int i = 0; i < this.row; i++) {for (int k = 0; k < b.col; k++) {for (int j = 0; j < this.col; j++) {temp += this.Data[i][j] * b.Data[j][k];}mul[i][k] = temp;temp = 0;}}Matrix another = new Matrix(this.row, b.col, mul);System.out.println("after multiply:");return another;}public Matrix transpose() {double tran[][] = new double[this.row][this.col];for (int i = 0; i < this.row; i++) {for (int j = 0; j < this.col; j++) {tran[j][i] = this.Data[i][j];}}Matrix another = new Matrix(this.col, this.row, tran);System.out.println("after transpose:");return another;}public String toString() {DecimalFormat df = new DecimalFormat("0");String result = "";// result += df.format(Date[0][0]);for (int i = 0; i < this.row; i++) {result += df.format(Data[i][0]);for (int j = 1; j < this.col; j++) {result += " " + df.format(Data[i][j]);}result += "\n";}return result;}
}public class Main {public static void main(String[] args) {Scanner scan = new Scanner(System.in);int row = scan.nextInt();int col = scan.nextInt();System.out.println("row:" + row + " column:" + col);// set valuedouble data[][] = new double[row][col];for (int i = 0; i < row; i++) {for (int j = 0; j < col; j++) {double d = scan.nextDouble();data[i][j] = d;}}Matrix matrix = new Matrix(row, col, data);int srow = scan.nextInt();int scol = scan.nextInt();double sv = scan.nextDouble();System.out.println("after set value:");matrix.setMatrix(srow, scol, sv);System.out.print(matrix);// get valueDecimalFormat df = new DecimalFormat("0");int vrow = scan.nextInt();int vcol = scan.nextInt();System.out.print("value on (" + vrow + "," + vcol + "):");System.out.println(df.format(matrix.getMatrix(vrow, vcol)));// addint addrow = scan.nextInt();int addcol = scan.nextInt();double addMatrix[][] = new double[addrow][addcol];for (int i = 0; i < addrow; i++) {for (int j = 0; j < addcol; j++) {double ad = scan.nextDouble();addMatrix[i][j] = ad;}}Matrix add = new Matrix(addrow, addcol, addMatrix);System.out.print(matrix.add(add));// mulint mulrow = scan.nextInt();int mulcol = scan.nextInt();double mulMatrix[][] = new double[mulrow][mulcol];for (int i = 0; i < mulrow; i++) {for (int j = 0; j < mulcol; j++) {double mu = scan.nextDouble();mulMatrix[i][j] = mu;}}Matrix mul = new Matrix(mulrow, mulcol, mulMatrix);// System.out.print(matrix.multiply(add));System.out.print(matrix.multiply(mul));// transposeSystem.out.print(matrix.transpose());}}

7-27 sdut-array1-2 RDMP音乐播放器(III)(一维数组)

注意: 这是在使用数组的情况下完成的。RDMP音乐播放器将存储m首歌曲,它们的名称将是以字母'A'开始的歌曲。(m<=26)
例如:M=3,则歌曲名称将是:'A','B','C' 。M=7,则歌曲名称将是:'A','B','C', D','E','F','G' 。RDMP有3个按钮,用户可以按下这些按钮来重新排列播放列表并播放歌曲。
举例:
如果,最初RDMP播放列表是“A, B, C, D, E”。3个控制按钮做以下工作:按钮1: 将播放列表的第一首歌曲移动到播放列表的末尾。例如:“A, B, C, D, E”会变成“B, C, D, E, A”。按钮2: 将播放列表的最后一首歌移动到播放列表的开始。例如,“A, B, C, D, E”会变成“E, A, B, C, D”。按钮3: 交换播放列表的前两首歌。例如,“A, B, C, D, E”会变成“B, A, C, D, E”。你需要编写一个程序来模拟一个可以按下n次按钮的RD音乐播放器。(n>0)

输入格式:

输入有多行。
首行是两个整数,分别为歌曲的数量m和按下播放按钮的次数n。
后续有n行整数,表示按下按扭的不同的操作,均为1到3之间的数字,代表要采取的行动。

输出格式:

输出最终播放列表的正确顺序。
歌曲名称中间用逗号作分隔。最后一首歌名称之后没有逗号。

输入样例1:

5 2
1
2

输出样例1:

A,B,C,D,E

输入样例2:

5 2
3
3

输出样例2:

A,B,C,D,E

输入样例3:

10 5
1
2
3
3
1

输出样例3:

B,C,D,E,F,G,H,I,J,A

答案:

import java.util.*;public class Main{public static void main(String [] args) {Scanner sc = new Scanner(System.in);int m = sc.nextInt();char a[] = new char [] {'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'};int n = sc.nextInt();for(int j = 0; j < n; j++) {int x = sc.nextInt();if(x == 1) {char temp = a[0];for(int i = 0; i <= m-2; i++) {a[i] = a[i+1];}a[m-1] = temp;}else if(x == 2) {char temp = a[m-1];for(int i = m-1; i >= 1; i--) {a[i] = a[i-1];}a[0] = temp;}else if(x == 3) {char temp = a[0];a[0] = a[1];a[1] = temp;}}for(int i = 0; i < m-1; i++) {System.out.print(a[i]+",");}System.out.println(a[m-1]);}
}

7-28 sdut-array2-2-局部峰值

给定一个N行乘N列的2D数组,逐行扫描该值并打印出所有局部峰值,该值大于其左上、上、右上、左、右、左下、下、右下的值(如果有)。

N的范围是2到150。

输入格式:
多组输入。每组输入包含两部分:

第一行包含整数N,表示2D数组的大小。

后面的N行中的每一行包含N个非负整数,用空格分隔。

输出格式:
对于每组输入,输出所有局部峰值按行顺序排列,每个局部峰值后跟一个空格。

如果没有局部峰值,则输出“none”。

每组输出之后加换行符。

输入样例:

2
5 1
1 0
2
5 2
2 3
3
5 5 5
0 5 0
5 5 5
3
1 2 5
2 3 2
4 2 3

输出样例:

5
5
none
5 4

答案:

import java.util.*;public class Main {public static void main(String[] args) {Scanner s = new Scanner(System.in);int[][] arr = new int[155][155];int i, j, n, flag;while (s.hasNextInt()) {n = s.nextInt();for (i = 1; i <= n; ++i) {for (j = 1; j <= n; ++j) {arr[i][j] = s.nextInt();}}flag = 0;for (i = 1; i <= n; ++i) {for (j = 1; j <= n; ++j) {if (IsMax(arr, i, j, n)) {// if(flag==1)// System.out.print(" ");System.out.print(arr[i][j] + " ");flag = 1;// System.out.println(i+" "+j);}}}if (flag == 0) {System.out.print("none");}System.out.println();}}public static boolean IsMax(int[][] arr, int a, int b, int n) {if (a - 1 >= 1 && b - 1 >= 1) // 左上if (arr[a][b] <= arr[a - 1][b - 1])return false;if (a - 1 >= 1)// 上if (arr[a - 1][b] >= arr[a][b])return false;if (a - 1 >= 1 && b + 1 <= n)// 右上if (arr[a - 1][b + 1] >= arr[a][b])return false;if (b - 1 >= 1)// 左if (arr[a][b - 1] >= arr[a][b])return false;if (b + 1 <= n)// 右if (arr[a][b + 1] >= arr[a][b])return false;if (a + 1 <= n && b - 1 >= 1)// 左下if (arr[a + 1][b - 1] >= arr[a][b])return false;if (a + 1 <= n)// 下if (arr[a + 1][b] >= arr[a][b])return false;if (a + 1 <= n && b + 1 <= n)// 右下if (arr[a + 1][b + 1] >= arr[a][b])return false;return true;}
}

7-29 sdut-array2-3 二维方阵变变变

有4行,4列的数据组成的矩阵。

1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16

它经过顺时针90度旋转后的效果为:(旋转角度值设为 90 )

13 9 5 1
14 10 6 2
15 11 7 3
16 12 8 4

顺时针180度旋转后的效果为:(旋转角度值设为 180 )

16 15 14 13
12 11 10 9
8 7 6 5
4 3 2 1

逆时针90度旋转后的结果为:(旋转角度值设为 -90 )

4 8 12 16
3 7 11 15
2 6 10 14
1 5 9 13

输入格式:
首行包括:(1)二维矩阵的行(列)数n,(2)矩阵旋转的角度,从90、180、-90中取一个;
接下来是n行n列的整数,数据之间以空格分隔,组成一个方阵。

输出格式:
矩阵按指定角度旋转后的结果。输出时按行、列进行组织。每行的数据之间有一个空格;行末尾数据后没有空格。

输入样例1:

4 90
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16

输出样例1:

13 9 5 1
14 10 6 2
15 11 7 3
16 12 8 4

输入样例2:

4 180
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16

输出样例2:

16 15 14 13
12 11 10 9
8 7 6 5
4 3 2 1

输入样例3:

4 -90
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16

输出样例3:

4 8 12 16
3 7 11 15
2 6 10 14
1 5 9 13

答案:

import java.util.*;public class Main{public static void main(String [] args) {Scanner sc = new Scanner(System.in);int n = sc.nextInt();int arr[][] = new int [n][n]; int a[][] = new int [n][n]; int m = sc.nextInt();for(int i = 0; i < n; i++) {for(int j = 0; j < n; j++) {arr[i][j] = sc.nextInt();}}if(m == 90) {for(int i = 0; i < n; i++) {for(int j = 0; j < n; j++) {a[i][j] = arr[n-j-1][i];}}}if(m == 180) {for(int i = 0; i < n; i++) {for(int j = 0; j < n; j++) {a[i][j] = arr[n-i-1][n-j-1];}}}if(m == -90) {for(int i = 0; i < n; i++) {for(int j = 0; j < n; j++) {a[i][j] = arr[j][n-i-1];}}}for(int i = 0; i < n; i++) {for(int j = 0; j < n-1; j++) {System.out.print(a[i][j]+" ");}System.out.println(a[i][n-1]);}}
}

7-30 sdut-array2-4 打印“杨辉三角“ 品中国数学史 增民族自豪感(1)

背景介绍: 北宋人贾宪约1050年首先使用“贾宪三角”进行高次开方运算。

南宋数学家杨辉在《详解九章算法》(1261年)记载并保存了“贾宪三角”,故称杨辉三角。杨辉三角是中国数学史上的一个伟大成就。
杨辉三角,是中国古代数学的杰出研究成果之一,它把二项式系数图形化,把组合数内在的一些代数性质直观地从图形中体现出来,是一种离散型的数与形的结合。

中国南宋数学家杨辉1261年所著的《详解九章算法》一书中出现。在欧洲,帕斯卡(1623----1662)在1654年发现这一规律,所以这个表又叫做帕斯卡三角形。帕斯卡的发现比杨辉要迟393年,比贾宪迟600年。

杨辉三角数字的特点为:

(1)在三角形的首列和对角线上,数值均为1;

(2)其余数据为:每个数字等于上一行的左右两个数字之和,第n+1行的第i个数等于第n行的第i-1个数和第i个数之和,用公式表示为: C(n+1,i)=C(n,i)+C(n,i-1)。

图示为:

杨辉三角的应用:(a+b)的n次方,展开式中的各项系数依次对应杨辉三角的第(n+1)行中的每一项。

输入格式:
欲打印杨辉三角的行数n(1<=n<=13)。

输出格式:
每个数字占据4个字符的位置,数字左对齐,数字不足4位的右边留出空格。

输入样例:

13

输出样例:

1
1   1
1   2   1
1   3   3   1
1   4   6   4   1
1   5   10  10  5   1
1   6   15  20  15  6   1
1   7   21  35  35  21  7   1
1   8   28  56  70  56  28  8   1
1   9   36  84  126 126 84  36  9   1
1   10  45  120 210 252 210 120 45  10  1
1   11  55  165 330 462 462 330 165 55  11  1
1   12  66  220 495 792 924 792 495 220 66  12  1

答案:

import java.util.*;public class Main {public static void main(String[] args) {Scanner sc = new Scanner(System.in);int n = sc.nextInt();int i,j;int [][] a = new int [n][n];for(i = 0; i < n; i++) {a[i][0] = 1;a[i][i] = 1;}for(i = 2; i < n; i++) {for(j = 1; j < i; j++) {a[i][j] = a[i-1][j]+a[i-1][j-1];}}for(i = 0; i < n; i++) {for(j = 0; j <= i; j++) {System.out.printf("%-4d",a[i][j]);}System.out.print("\n");}}
}

7-31 sdut-array2-5 打印“杨辉三角“ 品中国数学史 增民族自豪感(2)

背景介绍:

北宋人贾宪约1050年首先使用“贾宪三角”进行高次开方运算。
南宋数学家杨辉在《详解九章算法》(1261年)记载并保存了“贾宪三角”,故称杨辉三角。杨辉三角是中国数学史上的一个伟大成就。
杨辉三角,是中国古代数学的杰出研究成果之一,它把二项式系数图形化,把组合数内在的一些代数性质直观地从图形中体现出来,是一种离散型的数与形的结合。

中国南宋数学家杨辉1261年所著的《详解九章算法》一书中出现。在欧洲,帕斯卡(1623----1662)在1654年发现这一规律,所以这个表又叫做帕斯卡三角形。帕斯卡的发现比杨辉要迟393年,比贾宪迟600年。

杨辉三角数字的特点为:

(1)在三角形的首列和对角线上,数值均为1;

(2)其余数据为:每个数字等于上一行的左右两个数字之和,第n+1行的第i个数等于第n行的第i-1个数和第i个数之和,用公式表示为: C(n+1,i)=C(n,i)+C(n,i-1)。

图示为:

杨辉三角的应用:(a+b)的n次方,展开式中的各项系数依次对应杨辉三角的第(n+1)行中的每一项。

输入格式:
欲打印杨辉三角的行数n(1<=n<=13)。

输出格式:
(1)输出的数据为等腰三角形样式;

(2)每个数字占据4个字符的位置,数字左对齐,数字不足4位的右边留出空格;

(3)最后一行的数值“1”顶格,前面无空格。

提示:以n=5,分析行首空格数为:

输入样例1:

5

输出样例:

        1   1   1   1   2   1   1   3   3   1
1   4   6   4   1

输入样例2:

6

输出样例:

          1   1   1   1   2   1   1   3   3   1   1   4   6   4   1
1   5   10  10  5   1

答案:

import java.util.*;public class Main {public static void main(String[] args) {Scanner sc = new Scanner(System.in);int n = sc.nextInt();int i,j,k;int [][] a = new int [n][n];for(i = 0; i < n; i++) {a[i][0] = 1;a[i][i] = 1;}for(i = 2; i < n; i++) {for(j = 1; j < i; j++) {a[i][j] = a[i-1][j]+a[i-1][j-1];}}for(i = 0; i < n; i++) {for(k = 0; k < 2*(n-i-1); k++) {System.out.print(" ");}for(j = 0; j <= i; j++) {System.out.printf("%-4d",a[i][j]);}System.out.print("\n");}}
}

7-32 Shape类-2

定义一个形状类Shape,提供计算周长getPerimeter()和面积getArea()的函数
定义一个子类正方形类Square继承自Shape类,拥有边长属性,提供构造函数,能够计算周长getPerimeter()和面积getArea()
定义一个子类长方形类Rectangle继承自Square类,拥有长、宽属性,提供构造函数,能够计算周长getPerimeter()和面积getArea()
定义一个子类圆形类Circle继承自Shape,拥有半径属性,提供构造函数,能够计算周长getPerimeter()和面积getArea()

在main函数中,分别构造三个Shape类的变量,分别指向一个Square、Rectangle、Circle对象,并输出他们的周长、面积.

输入格式:
正方形类的边长
长方形类的长宽
圆类的半径

输出格式:
正方形的周长、面积
长方形的周长、面积
圆形的周长、面积

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

1
1 2
2

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

4.00 1.00
6.00 2.00
12.57 12.57

答案:

import java.util.*;abstract class Shape{abstract double getPerimeter();abstract double getArea();
}class Square extends Shape{double len;public Square(double len) {this.len = len;}public double getPerimeter() {return 4*len;}public double getArea() {return len*len;}
}class Rectangle extends Square{double broad;public Rectangle(double len,double broad) {super(len);this.broad = broad;}public double getPerimeter() {return 2*(len+broad);}public double getArea() {return len*broad;}
}class Circle extends Shape{double r;public Circle(double r) {this.r = r;}public double getPerimeter() {return 2*Math.PI*r;}public double getArea() {return Math.PI*r*r;}
}public class Main {public static void main(String[] args) {Scanner sc = new Scanner(System.in);double a = sc.nextDouble();Square s = new Square(a);System.out.printf("%.2f ",s.getPerimeter());System.out.printf("%.2f\n",s.getArea());double len = sc.nextDouble();double broad = sc.nextDouble();Rectangle re = new Rectangle(len,broad);System.out.printf("%.2f ",re.getPerimeter());System.out.printf("%.2f\n",re.getArea());double r = sc.nextDouble();Circle c = new Circle(r);System.out.printf("%.2f ",c.getPerimeter());System.out.printf("%.2f\n",c.getArea());}
}

7-33 学生、大学生、研究生类-2

修改题目125(学生类-本科生类-研究生类)
为学生类添加属性成绩,添加相应的get和set函数,添加函数getGrade()表示获得等级,该函数应当为抽象函数。
本科生和研究生的等级计算方式不同,如下所示

本科生标准 研究生标准
[80–100) A [90–100) A
[70–80) B [80–90) B
[60–70) C [70–80) C
[50–60) D [60–70) D
50 以下 E 60 以下 E

main函数中构造两个学生Student变量,分别指向本科生和研究生对象,调用getGrade()方法输出等级

输入格式:
本科生类信息,学号、姓名、性别、专业、成绩
研究生类信息,学号、姓名、性别、专业、导师、成绩

输出格式:
本科生等级
研究生等级

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

2 chen female cs 90
3 li male sc wang 80

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

A
B

答案:

import java.util.Scanner;public class Main {public static void main(String[] args) {Scanner scan = new Scanner(System.in);int no = scan.nextInt();String name = scan.next();String sex = scan.next();String major = scan.next();int score = scan.nextInt();CollegeStudent c = new CollegeStudent(no, name, sex, major,score);c.getGrade();no = scan.nextInt();name = scan.next();sex = scan.next();major = scan.next();String supervisor = scan.next();score = scan.nextInt();GraduateStudent g = new GraduateStudent(no, name, sex, major, supervisor,score);g.getGrade();scan.close();}
}abstract class Student {int no;String name;String sex;int score;public Student(int no, String name, String sex, int score) {this.no = no;this.name = name;this.sex = sex;this.score = score;}public int getNo() {return no;}public void setNo(int no) {this.no = no;}public String getName() {return name;}public void setName(String name) {this.name = name;}public String getSex() {return sex;}public void setSex(String sex) {this.sex = sex;}abstract void getGrade();public int getScore() {return score;}public void setScore(int score) {this.score = score;}public void attendClass(String className) {}public void print() {System.out.println("no: " + no);System.out.println("name: " + name);System.out.println("sex: " + sex);}
}class CollegeStudent extends Student {String major;public CollegeStudent(int no, String name, String sex, String major, int score) {super(no, name, sex, score);this.major = major;}public String getMajor() {return major;}public void setMajor(String major) {this.major = major;}public void print() {System.out.println("no: " + no);System.out.println("name: " + name);System.out.println("sex: " + sex);System.out.println("major: " + major);}public void getGrade() {if (score >= 80) {System.out.println("A");} else if (score >= 70) {System.out.println("B");} else if (score >= 60) {System.out.println("C");} else if (score >= 50) {System.out.println("D");} else {System.out.println("E");}}}class GraduateStudent extends CollegeStudent {String supervisor;public GraduateStudent(int no, String name, String sex, String major, String supervisor, int score) {super(no, name, sex, major, score);this.supervisor = supervisor;}public String getSupervisor() {return supervisor;}public void setSupervisor(String supervisor) {this.supervisor = supervisor;}public void doResearch() {System.out.println(name + " is doing research");}public void print() {System.out.println("no: " + no);System.out.println("name: " + name);System.out.println("sex: " + sex);System.out.println("major: " + major);System.out.println("supervisor: " + supervisor);}public void getGrade() {if (score >= 90) {System.out.println("A");} else if (score >= 80) {System.out.println("B");} else if (score >= 70) {System.out.println("C");} else if (score >= 60) {System.out.println("D");} else {System.out.println("E");}}
}

7-34 打球过程

利用模板方法来构造相关类实现下述过程:
各种球类的玩法虽然不同,但是球类比赛的过程是类似的,都包含如下几个步骤:
1球员报道–>2比赛开始–>3比赛–>4比赛结束–>5公布比赛成绩,且其中1 2 4步相同 第3步根据球类不同,玩法不同,第5步根据得分不同,公布方式结果不同
构造类BallMatch表示球类比赛,包含方法compete表示真个比赛过程
构造各个比赛过程的函数checkin,start,play,end,annouceResult
打印信息如下:
now checking in
now starting
now playing football
now ending
now annoucing result: 2-3
构造类FootballMatch和BasketBallMatch,实现具体的比赛过程。

在main函数中,读入整数i,如果为1,则构造一个足球比赛过程,如果为2则构造一个篮球比赛过程
打印比赛过程

输入格式:
比赛类型 比分

输出格式:
比赛过程信息

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

1 2-3

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

now checking in
now starting
now playing football
now ending
now annoucing result: 2-3

答案:

import java.util.*;public class Main {public static void main(String[] args) {Scanner scan = new Scanner(System.in);int type = scan.nextInt();BallMatch t = new BallMatch();if (type == 1) {FootballMatch f = new FootballMatch(scan.next());t.compete(f);} else if (type == 2) {BasketBallMatch b = new BasketBallMatch(scan.next());t.compete(b);}}
}class BallMatch {static void compete(Object o) {if (o instanceof FootballMatch) {FootballMatch f = (FootballMatch) o;f.checking();f.start();f.play();f.end();f.announce();} else if (o instanceof BasketBallMatch) {BasketBallMatch b = (BasketBallMatch) o;b.checking();b.start();b.play();b.end();b.announce();}}
}class FootballMatch {String score;public FootballMatch(String s) {this.score = s;}public void checking() {System.out.println("now checking in");}public void start() {System.out.println("now starting");}public void play() {System.out.println("now playing football");}public void end() {System.out.println("now ending");}public void announce() {System.out.println("now annoucing result: " + score);}
}class BasketBallMatch {String score;public BasketBallMatch(String s) {this.score = s;}public void checking() {System.out.println("now checking in");}public void start() {System.out.println("now starting");}public void play() {System.out.println("now playing basketball");}public void end() {System.out.println("now ending");}public void announce() {System.out.println("now annoucing result: " + score);}}

7-35 jmu-Java-04面向对象进阶-03-接口-自定义接口ArrayIntegerStack

定义IntegerStack接口,用于声明一个存放Integer元素的栈的常见方法:

public Integer push(Integer item);
//如果item为null,则不入栈直接返回null。如果栈满,也返回null。如果插入成功,返回item。public Integer pop();   //出栈,如果为空,则返回null。出栈时只移动栈顶指针,相应位置不置为null
public Integer peek();  //获得栈顶元素,如果为空,则返回null.
public boolean empty(); //如果为空返回true
public int size();      //返回栈中元素个数

定义IntegerStack的实现类ArrayIntegerStack,内部使用数组实现。创建时,可指定内部数组大小。

main方法说明
输入n,建立可包含n个元素的ArrayIntegerStack对象
输入m个值,均入栈。每次入栈均打印入栈返回结果。
输出栈顶元素,输出是否为空,输出size
使用Arrays.toString()输出内部数组中的值。
输入x,然后出栈x次,每次出栈均打印。
输出栈顶元素,输出是否为空,输出size
使用Arrays.toString()输出内部数组中的值。
思考
如果IntegerStack接口的实现类内部使用ArrayList来存储元素,怎么实现?测试代码需要进行什么修改?

输入样例

5
3
1 2 3
2

输出样例

1
2
3
3,false,3
[1, 2, 3, null, null]
3
2
1,false,1
[1, 2, 3, null, null]

答案:

import java.util.Arrays;
import java.util.Scanner;interface IntegerStack {public Integer push(Integer item); // 如果item为null,则不入栈直接返回null。如果栈满,也返回null。如果插入成功,返回itempublic Integer pop(); // 出栈,如果为空,则返回null。出栈时只移动栈顶指针,相应位置不置为nullpublic Integer peek(); // 获得栈顶元素,如果为空,则返回nullpublic boolean empty(); // 如果为空返回truepublic int size(); // 返回栈中元素个数
}class ArrayIntegerStack implements IntegerStack {private Integer[] arr;private int top = 0;public ArrayIntegerStack(int n) {arr = new Integer[n];Arrays.fill(arr, null);}public ArrayIntegerStack() {}@Overridepublic String toString() {return Arrays.toString(arr);}@Overridepublic Integer push(Integer item) {if (item == null || arr.length == top) {return null;}arr[top++] = item;return item;}@Overridepublic Integer pop() {if (top == 0) {return null;}return arr[--top];}@Overridepublic Integer peek() {if (top == 0) {return null;}return arr[top - 1];}@Overridepublic boolean empty() {return top == 0;}@Overridepublic int size() {return top;}
}public class Main {public static void main(String[] args) {Scanner s = new Scanner(System.in);int n = s.nextInt();ArrayIntegerStack ais = new ArrayIntegerStack(n);int m = s.nextInt();while (m-- > 0) {int item = s.nextInt();System.out.println(ais.push(item));}System.out.println(ais.peek() + "," + ais.empty() + "," + ais.size());System.out.println(ais);int x = s.nextInt();while (x-- > 0) {System.out.println(ais.pop());}System.out.println(ais.peek() + "," + ais.empty() + "," + ais.size());System.out.println(ais);}
}

7-36 USB接口的定义

定义一个USB接口,并通过Mouse和U盘类实现它,具体要求是:

1.接口名字为USB,里面包括两个抽象方法:

void work();描述可以工作

void stop(); 描述停止工作

2.完成类Mouse,实现接口USB,实现两个方法:

work方法输出“我点点点”;

stop方法输出 “我不能点了”;

3.完成类UPan,实现接口USB,实现两个方法:

work方法输出“我存存存”;

stop方法输出 “我走了”;

4测试类Main中,main方法中

定义接口变量usb1 ,存放鼠标对象,然后调用work和stop方法

定义接口数组usbs,包含两个元素,第0个元素存放一个Upan对象,第1个元素存放Mouse对象,循环数组,对每一个元素都调用work和stop方法。

输入格式:
输出格式:
输出方法调用的结果

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


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

我点点点
我不能点了
我存存存
我走了
我点点点
我不能点了

答案:

interface USB {void work();void stop();
}class Mouse implements USB {public void work() {System.out.println("我点点点");}public void stop() {System.out.println("我不能点了");}
}class UPan implements USB {public void work() {System.out.println("我存存存");}public void stop() {System.out.println("我走了");}
}public class Main {public static void main(String[] args) {USB usb1 = new Mouse();usb1.work();usb1.stop();USB[] usbs = new USB[2];usbs[0] = new UPan();usbs[1] = new Mouse();for (USB i : usbs){i.work();i.stop();}}
}

7-37 职工排序题

1. 为某保险公司设计一个职工管理系统,其中职工类的属性有:职工编号,姓名,性别,团体险业绩,个体险业绩;方法有:
每个属性对应的set,get方法;
不带参数的构造方法;
带参数的构造方法,完成对职工属性的初始化;
该类实现接口Comparable,完成对职工总业绩的比较。

2. 设计一个类,实现Comparator接口,完成对团体险业绩的比较;

3. 在Main类中,创建一个职工的线性表,分别完成对职工线性表按照总业绩升序排序,按照团体险业绩升序排序。
注意:不要设计键盘输入职工信息,可根据样例中提供的数据直接创建职工对象;

输入格式:
输出格式:
各项之间用逗号“,”分隔

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


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

编号,团险,个险,姓名,性别
1,500,400,职工1,female
3,600,300,职工3,male
2,400,600,职工2,female
4,800,200,职工4,female
5,500,700,职工5,male
编号,团险,个险,姓名,性别
2,400,600,职工2,female
1,500,400,职工1,female
5,500,700,职工5,male
3,600,300,职工3,male
4,800,200,职工4,female

答案:

import java.util.*;public class Main {public static void main(String[] args) {Worker t[] = new Worker[5];t[0] = new Worker(1, 500, 400, "职工1", "female");t[1] = new Worker(3, 600, 300, "职工3", "male");t[2] = new Worker(2, 400, 600, "职工2", "female");t[3] = new Worker(4, 800, 200, "职工4", "female");t[4] = new Worker(5, 500, 700, "职工5", "male");Arrays.sort(t);System.out.println("编号,团险,个险,姓名,性别");for (int i = 0; i < t.length; i++) {System.out.println(t[i].toString());}ArrayList<Worker> z = new ArrayList<Worker>();z.add(t[0]);z.add(t[1]);z.add(t[2]);z.add(t[3]);z.add(t[4]);Collections.sort(z, new compareAch());System.out.println("编号,团险,个险,姓名,性别");for (Worker y : z) {System.out.println(y.toString());}}
}class compareAch implements Comparator<Worker> {public int compare(Worker p1, Worker p2) {if (p1.getteam() > p2.getteam()) {return 1;} else if (p1.getteam() < p2.getteam()) {return -1;} else {return 0;}}
}class Worker implements Comparable<Worker> {private int id, team, personal;private String sex, name;public Worker(int id, int team, int personal, String name, String sex) {super();this.id = id;this.team = team;this.personal = personal;this.sex = sex;this.name = name;}public int getid() {return id;}public void setid(int id) {this.id = id;}public int getteam() {return team;}public void setteam(int team) {this.team = team;}public int getpersonal() {return personal;}public void setpersonal(int personal) {this.personal = personal;}public String getsex() {return sex;}public void setsex(String sex) {this.sex = sex;}public String getname() {return name;}public void setname(String name) {this.name = name;}@Overridepublic String toString() {return id + "," + team + "," + personal + "," + name + "," + sex;}@Overridepublic int hashCode() {final int prime = 31;int result = 1;result = prime * result + id;result = prime * result + personal;result = prime * result + team;result = prime * result + ((sex == null) ? 0 : sex.hashCode());result = prime * result + ((name == null) ? 0 : name.hashCode());return result;}@Overridepublic boolean equals(Object obj) {if (this == obj)return true;if (obj == null)return false;if (getClass() != obj.getClass())return false;Worker other = (Worker) obj;if (id != other.id)return false;if (personal != other.personal)return false;if (team != other.team)return false;if (sex == null) {if (other.sex != null)return false;} else if (!sex.equals(other.sex))return false;if (name == null) {if (other.name != null)return false;} else if (!name.equals(other.name))return false;return true;}public int compareTo(Worker w) {int i = (this.getpersonal() + this.getteam()) - (w.getpersonal() + w.getteam());if (i > 0) {i = 1;} else if (i < 0) {i = -1;} else {i = 0;}return i;}}

7-38 接口–四则计算器

利用接口做参数,写个计算器,能完成加减乘除运算。
1、定义一个接口ICompute含有一个方法int computer(int n, int m)。
2、定义Add类实现接口ICompute,实现computer方法,求m,n之和
3、定义Sub类实现接口ICompute,实现computer方法,求n-m之差
4、定义Main类,在里面输入两个整数a, b,利用Add类和Sub类的computer方法,求第一个数a和第二个数b之和,输出和,第一个数a和第二个数b之差,输出差。

输入格式:
输入在一行中给出2个整数

输出格式:
输出两个数的和、差

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

6 7

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

13
-1

答案:

import java.util.Scanner;public class Main{public static void main(String[] args) {Scanner in=new Scanner(System.in);int n=in.nextInt();int m=in.nextInt();Add l=new Add();Sub j=new Sub();System.out.println(l.computer(n, m));System.out.println(j.computer(n, m));in.close();}}
interface IComputer{abstract public int computer(int n ,int m);
}
class Add implements IComputer
{int m,n;public int computer(int n ,int m) {return n+m;}
}
class Sub implements IComputer
{int m,n;public int computer(int n ,int m) {return n-m;}
}

7-39 sdut-oop-7 答答租车系统(类的继承与多态 面向对象综合练习)

各位面向对象的小伙伴们,在学习了面向对象的核心概念——类的封装、继承、多态之后,答答租车系统开始营运了。

请你充分利用面向对象思想,为公司解决智能租车问题,根据客户选定的车型和租车天数,来计算租车费用,最大载客人数,最大载载重量。

公司现有三种车型(客车、皮卡车、货车),每种车都有名称和租金的属性;其中:客车只能载人,货车只能载货,皮卡车是客货两用车,即可以载人,也可以载货。

下面是答答租车公司的可用车型、容量及价目表:

要求:根据客户输入的所租车型的序号及天数,计算所能乘载的总人数、货物总数量及租车费用总金额。

输入格式:
首行是一个整数:代表要不要租车 1——要租车(程序继续),0——不租车(程序结束);

第二行是一个整数,代表要租车的数量N;

接下来是N行数据,每行2个整数m和n,其中:m表示要租车的编号,n表示租用该车型的天数。

输出格式:
若成功租车,则输出一行数据,数据间有一个空格,含义为:
载客总人数 载货总重量(保留2位小数) 租车金额(整数)
若不租车,则输出:
0 0.00 0(含义同上)

输入样例:

1
2
1 1
2 2

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

15 0.00 1600

答案:

import java.util.Scanner;class Car {public int num;public String model;public int person;public double ton;public int money;public Car() {this.num = 0;this.model = null;this.person = 0;this.ton = 0;this.money = 0;}public Car(int num, String model, int person, double ton, int money) {this.num = num;this.model = model;this.person = person;this.ton = ton;this.money = money;}public int getNum() {return num;}public void setNum(int num) {this.num = num;}public String getModel() {return model;}public void setModel(String model) {this.model = model;}public int getPerson() {return person;}public void setPerson(int person) {this.person = person;}public double getTon() {return ton;}public void setTon(int ton) {this.ton = ton;}public int getMoney() {return money;}public void setMoney(int money) {this.money = money;}public int getRant(int day) {return day * money;}
}public class Main {public static void main(String[] args) {Scanner scanner = new Scanner(System.in);Car[] car = new Car[11];car[1] = new Car(1, "A", 5, 0, 800);car[2] = new Car(2, "B", 5, 0, 400);car[3] = new Car(3, "C", 5, 0, 800);car[4] = new Car(4, "D", 51, 0, 1300);car[5] = new Car(5, "E", 55, 0, 1500);car[6] = new Car(6, "F", 5, 0.45, 500);car[7] = new Car(7, "G", 5, 2.0, 450);car[8] = new Car(8, "H", 0, 3, 200);car[9] = new Car(9, "I", 0, 25, 1500);car[10] = new Car(10, "J", 0, 35, 2000);int fg = scanner.nextInt();if (fg == 1) {int sumPer = 0, sumMon = 0;double sumTon = 0;int N = scanner.nextInt();for (int i = 0; i < N; i++) {int m = scanner.nextInt();int n = scanner.nextInt();sumPer += (car[m].person * n);sumTon += (car[m].ton * n);sumMon += (car[m].money * n);}System.out.println(sumPer + " " + String.format("%.2f", sumTon) + " " + sumMon);} else if (fg == 0) {System.out.println("0 0.00 0");}}
}

7-40 镜像字符串

镜像字符串是两个字符序列完全相反的字符串。从键盘录入两个不包含空格的字符串,判断第二个是否为第一个的镜像字符串,是则输出yes,否则输出no.

输入格式:
键盘录入的由一个空格分隔的两个字符串

输出格式:
yes(no)

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

abc cba

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

yes

答案:

import java.util.Scanner;
public class Main{public static void main(String[] args) {Scanner cin=new Scanner(System.in);String s1=cin.next();String s2=cin.next();String ns1=new StringBuffer(s1).reverse().toString();if(ns1.equals(s2))System.out.println("yes");else System.out.println("no");cin.close();}
}

7-41 字符串

对于输入字符串s(假设字符串只包含字母构成的单词和空格),完成如下功能:

1、统计该字符串中字母c出现的次数
2、求该字符串的逆
3、输出该字符串中子串str的所有位置(无需考虑子串叠加现象)
4、将字符串中每个单词的第一个字母变成大写并输出

输入格式:
字符串s
字母c
子串str

输出格式:
c在s中出现的次数
s的逆
str在s中的所有位置
所有单词首字母大写后的字符串

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

I scream you scream we all scream for icecream
m
eam

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

4
maerceci rof maercs lla ew maercs uoy maercs I
5 16 30 43
I Scream You Scream We All Scream For Icecream

答案:

import java.util.Scanner;
public class Main {public static void main(String[] args) {Scanner sc=new Scanner(System.in);String s=sc.nextLine();String strc=sc.nextLine();//待输入字母,因为Java中没有直接读取单个字符的函数,//所以将字母输入到字符串中,调用String中的charAt()函数//取第一个字符即为我们想要输入的单个字符char c=strc.charAt(0);String str=sc.nextLine();char []ns=s.toCharArray();int count=0;// System.out.println(ns);for (int i = 0; i < ns.length ; i++) {if(ns[i]==c){count++;}}System.out.println(count);for (int i = 0; i < ns.length/2 ; i++) {char temp=ns[i];ns[i]=ns[ns.length-i-1];ns[ns.length-i-1]=temp;}System.out.println(ns);int head=0;int []arr=new int[s.length()];String []nns=s.split(" ");//将句子中的各个单词分隔int j=0;int preStrLength=0;while(true){//indexOf——返回指定字符第一次出现的字符串内的索引int n = s.indexOf(str);//找不到返回-1,循环结束if (n == -1) {break;}//存储找到的值(下标)//arr[j++]=n;//第一次head=0,从0开始找,之后head变为下标n+要找字符串的长度//应该从这里开始查找该子串,不加长度会出问题的!//head = n + str.length();if(j != 0)System.out.print(' ');//break;System.out.print((n + preStrLength));//字符串位置j++;s= s.substring(n +str.length());//截取preStrLength +=(n +str.length());}
//        System.out.print(arr[0]);
//        for (int i = 1; i < j ; i++) {//            System.out.print(" " + arr[i]);
//        }System.out.println();String s1=new String();for (int i = 0; i < nns.length ; i++) {if(i==nns.length-1)s1+=nns[i].substring(0,1).toUpperCase()+nns[i].substring(1);elses1+=nns[i].substring(0,1).toUpperCase()+nns[i].substring(1)+" ";}System.out.println(s1);sc.close();}
}

7-42 各类字符数

从键盘输入一个字符串,程序输出该字符串中的大写英文字母数,小写英文字母数以及非英文字母数

输入格式:
字符串

输出格式:
大写英文字母数
小写英文字母数
非英文字母数

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

Hello My Dear Friend, I Miss You Very Much!

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

9
24
10

答案:

import java.util.Scanner;
public class Main {public static void main(String []args){Scanner cin=new Scanner(System.in);String s=cin.nextLine();char[]ns =s.toCharArray();int upcount=0;int lowcount=0;int count=0;for(int i=0;i<ns.length;i++){if(ns[i]>=65&&ns[i]<=90)upcount++;else if(ns[i]>=97&&ns[i]<=122){lowcount++;}else count++;}System.out.println(upcount);System.out.println(lowcount);System.out.println(count);cin.close();}
}

7-43 数据类型判断

从键盘分别输入通过空格分割的整型(int)、浮点型(double)、字符型(String)、布尔型(boolean),根据读取的内容判断他们的类型并将他们解析为正确的对象,并都放到一个数组中。输出各个对象的类型

输入格式:
字符串

输出格式:
数据类型

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

2.1 true 123 abcde

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

double boolean int String

答案:

import java.util.Scanner;
public class Main {public static void main(String []args){Scanner cin=new Scanner(System.in);String s;int j=0;while(cin.hasNext()){if(j!=0)System.out.print(" ");if(cin.hasNextInt()){System.out.print("int");}else if(cin.hasNextDouble()){System.out.print("double");}else if(cin.hasNextBoolean()){System.out.print("boolean");}else System.out.print("String");cin.next();j=1;}}
}

7-44 打印双休日

输入年份和月份,打印当月所有双休日日期,打印格式为:“2018-06-16”

输入格式:
年份和月份

输出格式:
双休日日期

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

2018 6

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

2018-06-02
2018-06-03
2018-06-09
2018-06-10
2018-06-16
2018-06-17
2018-06-23
2018-06-24
2018-06-30

答案:

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Scanner;public class Main{public static void main(String[] args) throws ParseException {Scanner in = new Scanner(System.in);String str = in.nextLine();SimpleDateFormat for1=new SimpleDateFormat("yyyy MM");SimpleDateFormat for2=new SimpleDateFormat("yyyy-MM-dd");Calendar cal=Calendar.getInstance();cal.clear(); cal.setTime(for1.parse(str));for(int i=0;i<cal.get(Calendar.DAY_OF_MONTH);i++){if(cal.get(Calendar.DAY_OF_WEEK)==Calendar.SUNDAY || cal.get(Calendar.DAY_OF_WEEK)==Calendar.SATURDAY) {System.out.println(for2.format(cal.getTime()));}cal.add(Calendar.DAY_OF_MONTH, 1);}}
}

7-45 比较日期

从命令行输入两个日期(格式为MM,dd,yyyy),程序解析日期,判断两个日期的大小,以及两个日期的间隔天数。
提示:月份是从0开始

输入格式:
两个日期

输出格式:
日期大小关系
间隔天数(正数)

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

04,12,2012 04,21,2012

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

<
9

答案:

import java.util.*;
import java.text.SimpleDateFormat;
import java.text.ParseException;public class Main{public static void main(String []args) throws ParseException{Scanner cin=new Scanner(System.in);String str1=cin.next();String str2=cin.next();SimpleDateFormat df=new SimpleDateFormat("MM,dd,yyyy");Date d1=df.parse(str1);Date d2=df.parse(str2);char a;if(d1.after(d2)) a='>';else if(d1.before(d2)) a='<';else a='=';System.out.println(a);int b= (int) ((d2.getTime() - d1.getTime()) / (1000 * 60 * 60 * 24));//毫秒转化为天数System.out.println(Math.abs(b));cin.close();}
}

7-46 我也会加密

字符串加密可以理解为对字符串的一种固定方式的变形,现定义一种基于种子数字的加密方法,首先计算种子数字,计算方法为将该字符串的长度对5求余加1,以该数字为间隔,得到原字符串的子串并求逆得到最终的密码。

输入格式:
原字符串

输出格式:
加密后的字符串

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

abcdefghijklmn

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

kfa

答案:

import java.util.*;public class Main {public static void main(String[] args) {Scanner sc = new Scanner(System.in);String s1 = sc.nextLine();StringBuilder s2 = new StringBuilder(s1);int length = s1.length();int seed = length % 5 + 1;StringBuilder s3 = new StringBuilder();for (int i = 0; i < length; i += seed) {s3.append(s2.charAt(i));}System.out.print(s3.reverse());sc.close();}
}

7-47 将一整个正整数的所有位重新排序,组成一个最大数

输入一个正整数,将这个数的所有位进行重新排序,得出最大的值。

输入格式:
输入一个正整数

输出格式:
输出排序后最大的值

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

19837

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

98731

答案:

import java.util.Arrays;
import java.util.Scanner;public class Main {public static void main(String[] args) {Scanner s = new Scanner(System.in);int a = s.nextInt();int[] num = new int[(a + "").length()];for (int i = 0; i < num.length; i++) {num[i] = a % 10;a /= 10;}Arrays.sort(num);for (int i = num.length-1; i >= 0; i--) {System.out.print(num[i]);}}
}

7-48 jmu-Java-02基本语法-03-身份证排序

1、输入n,然后连续输入n个身份证号。
2、然后根据输入的是sort1还是sort2,执行不同的功能。输入的不是sort1或sort2,则输出exit并退出。
输入sort1,将每个身份证的年月日抽取出来,按年-月-日格式组装,然后对组装后的年-月-日升序输出。
输入sort2,将所有身份证按照里面的年月日升序输出。
注意:处理输入的时候,全部使用Scanner的nextLine()方法,以免出错。

输入样例:

6
410425198309308225
320203197206115011
431227196108033146
330226196605054190
34080019810819327X
320111197112301539
sort1
sort2
e

输出样例:

1961-08-03
1966-05-05
1971-12-30
1972-06-11
1981-08-19
1983-09-30
431227196108033146
330226196605054190
320111197112301539
320203197206115011
34080019810819327X
410425198309308225
exit

7-49 单词在句子中的位置

给定英文句子,编写方法void wordPositions(String sentence),该方法中计算sentence中的每个单词在句子中的起始位置和单词长度并输出。假设句子中只包含英文字母和空格,且单词不重复。

输入格式:
句子

输出格式:
每个单词在句子中的起始位置和单词长度

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

Why are you so crazy about java

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

Why: 0, 3
are: 4, 3
you: 8, 3
so: 12, 2
crazy: 15, 5
about: 21, 5
java: 27, 4

答案:

import java.util.*;public class Main {public static void main(String[] args) {Scanner sc = new Scanner(System.in);String s = sc.nextLine();Statistics st = new Statistics();st.wordPositions(s);sc.close();}
}class Statistics {int[] count;// 统计单词长度String[] ns;// 纪录单词List<Integer> pos = new LinkedList<>();// 记录单词出现位置public Statistics() {count = new int[100];}public void wordPositions(String sentence) {for (int i = 0; i < sentence.length(); i++) {if (i == 0) {pos.add(i);} else if (sentence.charAt(i - 1) == ' ') {pos.add(i);}}ns = sentence.split(" ");// 将句子转化为字符串数组for (int i = 0; i < ns.length; i++) {count[i] = ns[i].length();}for (int i = 0; i < ns.length; i++) {System.out.println(ns[i] + ": " + pos.get(i) + ", " + count[i]);}}
}

7-50 学生Map

编写学生类,包含学号no、姓名name、成绩score,提供必要的构造函数、toString函数和equals/hashcode函数,其中,toString函数的格式为“no:xxx name:xxx score:xxx”,no参与equals和hashcode的计算 在main函数中构造一个Map容器存放学生对象 从命令行输入多个学生对象,存入Map中,其中key为学号,value为学生对象。 从命令行中读入在学生集合上的操作,具体操作包含: add 添加一个学生(包含学号和学生姓名) delete 删除一个学生(包含学号) set 修改一个学生信息(只修改某学号学生的成绩) 完成操作后按学生的学号从小到大的顺序输出所有学生的信息
输出时按照学生的学号顺序输出

输入格式:
学生个数
学生对象数据
操作数
操作内容

输出格式:
按照学号顺序输出集合中的学生

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

4
1 wong 90
2 liu 80
3 chen 70
4 fang 60
3
add 5 duan 80
delete 3
set 4 70

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

no:1 name:wong score:90
no:2 name:liu score:80
no:4 name:fang score:70
no:5 name:duan score:80

答案:

import java.util.*;
public class Main {public static void main(String[] args) {// TODO Auto-generated method stubScanner in=new Scanner(System.in);int n=in.nextInt();Map<Integer,Student> m=new HashMap<Integer,Student>();for(int i=0;i<n;i++) {int a=in.nextInt();Student ss=new Student(a,in.next(),in.nextInt());m.put(a,ss);}int mm=in.nextInt();for(int i=0;i<mm;i++) {String test=in.next();if(test.equals("add")) {int no=in.nextInt();Student sss=new Student(no,in.next(),in.nextInt());m.put(no, sss);}else if(test.equals("delete")) {int no=in.nextInt();m.remove(no);}else if(test.equals("set")) {int no=in.nextInt();int score=in.nextInt();for(Integer ii:m.keySet()) {//keyset遍历if(ii.intValue()==no) {m.get(ii).setScore(score);break;}}}}for(Integer ii:m.keySet()) {System.out.println(m.get(ii));}}
}class Student{int no;String name;int score;public Student(int no,String name,int score) {this.no=no;this.name=name;this.score=score;}public void setScore(int score) {this.score=score;}@Overridepublic String toString() {//no:xxx name:xxx score:xxxreturn "no:"+this.no+" name:"+this.name+" score:"+this.score;}@Overridepublic boolean equals(Object o) {if(o==null)return false;Student ss=(Student)o;if(this.no==ss.no) {return true;}else {return false;}}@Overridepublic int hashCode() {int i=11;i=i*31+this.no;return i;}
}class sortByNo implements Comparator<Student>{public int compare(Student s1,Student s2) {return s1.no-s2.no;}
}

7-51 sdust-Java-字符串集合求并集

从键盘接收N个英文字符串(其中不同的字符串数量大于10),从头开始取5个不同的字符串放入一个集合S1,然后接着取5个不同的字符串放入另一个集合S2,按照字母顺序输出S1和S2的并集中的每个字符串(字符串区分大小写)

输入格式:
一行以空格分开的英文字符串(不同的字符串数量大于10)。

输出格式:
按照字母顺序(先比较字符串首字母,首字母相同的比较字符串第二个字母,以此类推)输出的S1和S2并集的字符串。

输入样例:

android python java javaee javase database java jsp servlet java algorithm junit

输出样例:

algorithm
android
database
java
javaee
javase
jsp
python
servlet

答案:

import java.util.*;
public class Main {public static void main(String[] args) {String[] s = new String[15];Scanner sc = new Scanner(System.in);TreeSet<String> a = new TreeSet<String>();TreeSet<String> b = new TreeSet<String>();String ss = sc.nextLine();for (String i : ss.split(" ")) {if (a.size() < 5) {a.add(i);continue;}if (b.size() < 5) {b.add(i);continue;}}a.addAll(b);for (String i : a) {System.out.println(i);}sc.close();}
}

7-52 手机按价格排序、查找

编写手机类(MobilePhone),含有type(型号,String类型)、price(价格,int类型)属性,要求该类实现Comparable接口,重写compareTo方法,实现按照price的大小来确定两个手机对象的大小关系。

在链表中添加三个手机对象(从键盘输入),通过Collections类的sort方法对链表中的对象按照price升序排序。输入第四个手机对象的信息,并查找它的price是否与链表中某个对象的price相同。

输入格式:
先输入三部手机的型号、价格信息
再输入要查找的第四部手机的型号、价格信息
每部手机信息的格式如:Redmi9A 599

输出格式:
先输出三部手机排序前的信息
再输出三部手机排序后的信息
最后输出第四部手机是否与前面某部手机价格相同
具体格式参考输出样例

输入样例1:
在这里给出一组输入,第四部手机与前三部中某一部价格相同。例如:

HONOR70  2699
MI12  3499
VIVOS15  3299
RedmiK50  2699

输出样例1:
在这里给出相应的输出,第四部手机与前三部中某一部价格相同。例如:

排序前,链表中的数据:
型号:HONOR70,价格:2699
型号:MI12,价格:3499
型号:VIVOS15,价格:3299
排序后,链表中的数据:
型号:HONOR70,价格:2699
型号:VIVOS15,价格:3299
型号:MI12,价格:3499
RedmiK50与链表中的HONOR70价格相同

输入样例2:
在这里给出一组输入,第四部手机与前面三部的价格都不同。例如:

RedmiNote9  1349
HonorX30 1699
VIVOT2X  1599
OPPOk10  2199

输出样例2:
在这里给出相应的输出,第四部手机与前面三部的价格都不同。例如:

排序前,链表中的数据:
型号:RedmiNote9,价格:1349
型号:HonorX30,价格:1699
型号:VIVOT2X,价格:1599
排序后,链表中的数据:
型号:RedmiNote9,价格:1349
型号:VIVOT2X,价格:1599
型号:HonorX30,价格:1699
链表中的对象,没有一个与OPPOk10价格相同的

答案:

import java.util.*;class MobilePhone implements Comparable<MobilePhone> {String type;int price;public MobilePhone(String type,int price) {this.type = type;this.price = price;}public int compareTo(MobilePhone o) {return this.price - o.price;}
}public class Main {public static void main(String[] args) {Scanner cin = new Scanner(System.in);List<MobilePhone> list = new LinkedList<MobilePhone>();for(int i = 0;i < 3;i++) {list.add(new MobilePhone(cin.next(),cin.nextInt()));}Iterator<MobilePhone> iterator = list.iterator();System.out.println("排序前,链表中的数据:");while(iterator.hasNext()){MobilePhone s = iterator.next();System.out.println("型号:"+s.type+","+"价格:"+s.price);}Collections.sort(list);System.out.println("排序后,链表中的数据:");iterator = list.iterator();while(iterator.hasNext()){MobilePhone s = iterator.next();System.out.println("型号:"+s.type+","+"价格:"+s.price);}MobilePhone demo = new MobilePhone(cin.next(),cin.nextInt());int index = Collections.binarySearch(list,demo,null);if(index>=0){System.out.println(demo.type+"与链表中的"+list.get(index).type+"价格相同");}else {System.out.println("链表中的对象,没有一个与"+demo.type+"价格相同的");}}}

7-53 jmu-Java-05集合-4-倒排索引

对若干行文字建立倒排索引(根据单词找到所在行号)。
然后根据关键字,在倒排索引查找进行查找,找到包含所有该关键字所在的行数并输出。

输入说明
1、若干行英文,以!!!为结束。
2、输入一行查询关键字,以1个空格为分隔
输出说明
1、输出所创建倒排索引。索引的key按照字母升序,索引的value按照行号升序
2、输出查询结果。如果找到,输出行集与行集内每一行的内容,如果没找到输出found 0 results

输入样例

where are you from are you ok
this is a test
that is an apple
there are lots of apples you eat it
who are you
!!!!!
you are
eat
you test
abc

输出样例

a=[2]
an=[3]
apple=[3]
apples=[4]
are=[1, 4, 5]
eat=[4]
from=[1]
is=[2, 3]
it=[4]
lots=[4]
of=[4]
ok=[1]
test=[2]
that=[3]
there=[4]
this=[2]
where=[1]
who=[5]
you=[1, 4, 5]
[1, 4, 5]
line 1:where are you from are you ok
line 4:there are lots of apples you eat it
line 5:who are you
[4]
line 4:there are lots of apples you eat it
found 0 results
found 0 results

7-54 测试抛出异常

尝试构造类ArrayUtil,该类的方法int findMax(int[] arr, int begin, int end)能抛出IllegalArgumentException(表示参数错误)的方法。
正常执行要求begin<=end

如果begin>=end,抛出异常(IllegalArgumentException),异常信息为 “begin:x >= end:x”

如果begin<0,抛出异常(IllegalArgumentException),异常信息为 “begin:x < 0”

如果end>arr.length,抛出异常(IllegalArgumentException),异常信息为 “end:x > arr.length”

要求在findMax方法声明处声明此异常,在main函数里要捕获此异常,并输出异常类型(可用obj.getClass().getName())和异常信息

输入格式:
输入n,表示int数组大小

输入n个整数,放入数组。

输入m,表示begin和end的对数

输入m对整数,代表begin与end,然后调用ArrayUtils.findMax方法。

输出格式:
异常信息

数组的最大值

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

5
1 2 3 4 5
6
0 5
3 3
3 4
3 2
-1 3
0 6

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

5
java.lang.IllegalArgumentException: begin:3 >= end:3
4
java.lang.IllegalArgumentException: begin:3 >= end:2
java.lang.IllegalArgumentException: begin:-1 < 0
java.lang.IllegalArgumentException: end:6 > arr.length

答案:

import java.util.*;
public class Main {public static void main(String[] args) {// TODO Auto-generated method stubScanner in = new Scanner(System.in);int n = in.nextInt();int[] a = new int[n];  for(int i = 0;i < n;i++) {a[i] = in.nextInt();}int m = in.nextInt();ArrayUtil c = new ArrayUtil();for(int i = 0;i < m;i++) {int b = in.nextInt();int e = in.nextInt();c.findMax(a, b, e);}}
}class ArrayUtil{public ArrayUtil(){}public void findMax(int[] arr,int begin, int end) {if(begin >= end) {System.out.println("java.lang.IllegalArgumentException: begin:"+begin+" >= end:"+end);}else if(begin < 0) {System.out.println("java.lang.IllegalArgumentException: begin:"+begin+" < 0");}else if(end > arr.length) {System.out.println("java.lang.IllegalArgumentException: end:"+end+" > arr.length");}else {int max = -999;for(int i = begin;i<end;i++) {if(arr[i]>max) {max = arr[i];}}System.out.println(max);}}}

7-55 较为复杂情况下的求和

计算一个给定序列的整数和,序列中可能会混入无关的字母,求和的时候需要忽略。

输入格式:
输入为一行,元素直接使用空格分割。

输出格式:
输出为序列整数部分的和。

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

1 2 3 a 4 5

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

15

答案:

import java.util.Scanner;
public class Main {public static void main(String[] args) {int sum = 0;Scanner sc = new Scanner(System.in);String s = sc.nextLine();String[] split = s.split(" ");for (int i = 0; i < split.length; i++) {try {              sum += Integer.parseInt(split[i]);}catch (Exception e){continue;}        }        System.out.println(sum);}
}

7-56 InputMismatchException异常

(InputMismatchException异常)编写一个程序,提示用户读取两个整数,然后显示它们的和。程序应该在输入不正确时提示用户再次读取数值。

输入格式:
输入多组两个数

输出格式:
输出两个数的和

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

1  3
2.0  3
3.0  4
4  5

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

sum = 4
Incorrect input: two integer is required
Incorrect input: two integer is required
sum = 9

答案:

import java.util.*;
public class Main {public static void main(String[] args) {Scanner in = new Scanner(System.in);while(true) {try {int a = in.nextInt();int b = in.nextInt();System.out.println("sum = "+(a+b));}catch(InputMismatchException e) {System.out.println("Incorrect input: two integer is required");in.nextLine();}}}
}

7-57 设计一个Tiangle异常类

创建一个IllegalTriangleException类,处理三角形的三边,任意两边之和小于等于第三边,则显示三条边不符合要求。
然后设计一个有三条边的Triangle的类。如果三条边不符合要求,则抛出一个IllegalTriangleException异常。
三角形的构造方法如下:

public Triangle(double side1, double side2, double side3) throws IllegalTriangleException {//实现
}

一个名为toString()的方法返回这个三角形的字符串描述。
toString()方法的实现如下所示:

return "Triangle [side1=" + side1 + ", side2=" + side2 + ", side3=" + side3 + "]";

编写一个测试程序如下,用户输入三角形的三条边,然后显示相应信息。
提交时,将此测试程序附在后面一起提交。
测试程序:

public class Main{public static void main(String[] args) {Scanner input = new Scanner(System.in);double s1 = input.nextDouble();double s2 = input.nextDouble();double s3 = input.nextDouble();try {Triangle t = new Triangle(s1,s2,s3);System.out.println(t);}catch (IllegalTriangleException ex) {System.out.println(ex.getMessage());}}
}

输入格式:
输入三条边

输出格式:
如果三条边正确,则输出toString()的信息,否则,输出IllegalTriangleException: 非法的边长
例如,输入1 1 1,则输出Triangle [side1=1.0, side2=1.0, side3=1.0]
若输入 1 2 3,则输出Invalid: 1.0,2.0,3.0

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

1 2 3

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

Invalid: 1.0,2.0,3.0

答案:

import java.util.*;
public class Main{public static void main(String[] args) {Scanner input = new Scanner(System.in);double s1 = input.nextDouble();double s2 = input.nextDouble();double s3 = input.nextDouble();try {Triangle t = new Triangle(s1,s2,s3);System.out.println(t);}catch (IllegalTriangleException ex) {System.out.println(ex.getMessage());}}
}
class IllegalTriangleException extends Exception{private double side1;private double side2;private double side3;public IllegalTriangleException(double side1,double side2 ,double side3) {super("Invalid: "+side1+","+side2+","+side3);this.side1=side1;this.side2=side2;this.side3=side3;}
}
class Triangle{private double side1;private double side2;private double side3;public Triangle(double side1,double side2,double side3) throws IllegalTriangleException{if((side1+side2)>side3&(side1+side3)>side2&(side2+side3)>side1) {this.side1=side1;this.side2=side2;this.side3=side3;}elsethrow new  IllegalTriangleException(side1,side2,side3);}@Overridepublic String toString(){return "Triangle ["+"side1="+this.side1+", side2="+this.side2+", side3="+this.side3+"]";}
}

7-58 自定义异常:超载异常(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;class OverLoadException extends Exception{private String message;@Overridepublic String getMessage() {return message;}public void setMessage(String message) {this.message = message;}public OverLoadException(double n) {this.message = "无法再装载重量是" + n + "吨的集装箱";}public void showMessage() {System.out.println(this.message);}
}class CargoShip {private double actualWeight = 0;private double maxWeight;public double getActualWeight() {return actualWeight;}public void setActualWeight(double actualWeight) {this.actualWeight = actualWeight;}public double getMaxWeight() {return maxWeight;}public void setMaxWeight(double maxWeight) {this.maxWeight = maxWeight;}public void loading(double weight) throws OverLoadException {this.actualWeight += weight;if (actualWeight > maxWeight) {throw new OverLoadException(weight);}System.out.println("目前共装载了" + actualWeight + "吨货物");}
}class Main {public static void main(String[] args) {CargoShip myship = new CargoShip();Scanner scanner = new Scanner(System.in);double maxWeight = scanner.nextDouble();myship.setMaxWeight(maxWeight);try {double weight1 = scanner.nextDouble();myship.loading(weight1);double weight2 = scanner.nextDouble();myship.loading(weight2);}catch (OverLoadException e) {e.showMessage();}finally {System.out.println("货船将正点起航");}}
}

Java期末复习题目合集相关推荐

  1. 【2021年最新版Java校招面试题目合集】

    1.什么是Java虚拟机?为什么Java被称作是"平台无关的编程语言"? Java虚拟机是一个可以执行Java字节码的虚拟机进程.Java源文件被编译成能被Java虚拟机执行的字节 ...

  2. 最强Java面试题全部合集,涵盖BAT大厂面试必考的9大技术!-强烈建议收藏

    过去2年我持续分享了BAT TMD为代表的大厂最新面试题目,特别是蚂蚁金服.天猫.淘宝.头条.拼多多等Java面试题目. 过去2年,我已经成功的帮助了部分同学进入了大厂. 2020开始,我依然会为大家 ...

  3. 京东java笔试_2017阿里,百度,京东java面试+笔试大合集,2018的你会吗?

    2017阿里,百度,京东java面试+笔试大合集 1.阿里 面试(一二面合集) 1.介绍一下你自己. 2.介绍一下你认为做的最好的一个项目. 3.请用五分钟的时间把你做的项目的流程图画一下. 4.项目 ...

  4. 20210325:力扣递归,回溯类型题目合集

    力扣递归,回溯类型题目合集 题目 思路与算法 代码实现 写在最后 题目 子集 2. 90. 子集 II 3. 40. 组合总和 II 4. 22. 括号生成 思路与算法 子集:注释的很详细,递归生成子 ...

  5. 20210322 :贪心思想力扣典型题目合集

    贪心思想力扣典型题目合集 写在前面 题目列表 思路分析 代码实现 写在前面 贪心的思想很多时候在于想到那个贪心的点上,而对徒手书写某些代码结构的能力并不做要求,个人认为需要的是你敏锐的意识到这个贪心的 ...

  6. 20210310 20210311 :栈、队列、堆类题目合集

    栈.队列.堆类题目合集 写在前面 题目列表 思路分析 代码实现 写在前面 栈.队列.堆基本的题目就是这些,需要特殊技巧的另算,重写一遍保证熟练掌握这些题目并且达到熟练使用的程度.记录以便后续再次学习. ...

  7. 牛客网-精华专题-前端校招面试题目合集

    前端校招面试题目合集 501 HTML CSS 前端基础 HTML 浏览器页面有哪三层构成,分别是什么,作用是什么? 构成:结构层(structural layer).表示层(presentation ...

  8. 中高级面试题题目合集

    题目合集持续更新ing- 前端基础github地址.README.md可以下载到typora中打开,会有整个大纲目录显示(github中markdown目录快捷生成方式不现实,之后可能会想办法生成贴过 ...

  9. java switch case怎么判断范围_【转】Java期末复习攻略!

    期末 19年就这样要过去了, 终于到了小时候作文里的未来呢! 然而,期末考试也随之来临了. 不知大家"预习"的怎么样呢? 期末复习资料的放送快接近尾声了 下面康康学长学姐们 怎么教 ...

最新文章

  1. 【经验】如何查看gcc、g++不加-std时的默认版本
  2. 【人物】徐磊:对用户驯养,只需要让用户记得你会给肉
  3. Foundations of Machine Learning: Rademacher complexity and VC-Dimension(2)
  4. 百度地图得到两地点(通过经纬度)的距离、 通过经纬度获取详细地址
  5. 尾调用优化 java_基于Java8函数式编程求一个List的全部子集|尾调用优化解决递归性能问题...
  6. linux下mysql的忘记root密码的解决办法
  7. uploadify 上传文件出现HTTP 404错误
  8. spring mvc 4.3.2 + mybatis 3.4.1 + mysql 5.7.14 +shiro 幼儿园收费系统 之 消息管理
  9. 前端使用js压缩图片上传
  10. CentOS7服务器安装GPU显卡驱动和CUDA简单方法
  11. Java中枚举类的ordinal()方法
  12. BitCoin p2p通信过程
  13. 昨夜星辰昨夜风,只因见您在梦中
  14. bam文件读取_bam格式文件处理大全(一)
  15. assigning the result of this type assertion to a variable could eliminate the followin assertion解决
  16. 基于Atmel128A单片机的MP31.0设计
  17. 【故障诊断分析】基于matlab小波变换外圈轴承故障诊断【含Matlab源码 1678期】
  18. MVVM设计模式的大体布局框架
  19. Mysql数据库备份——数据库备份和表备份
  20. 实验二 信号与系统Matlab 求系统的冲激响应、阶跃响应、零状态响应

热门文章

  1. 计算机丢失logmanager dll,修复logmanager.dll
  2. 苹果LiDAR 3D传感方案专利曝光
  3. 鱼c论坛 python课后题pdf_[全套55讲]鱼C论坛小甲鱼Python的课后题.pdf
  4. RadioButton+Fragment和XlistView及多条目加载
  5. JDBC完成对数据库数据操作(增,删,改,查)
  6. 【转】Java8 函数式编程详解
  7. 有道打赏视频/支付已对接/自带资源
  8. 双面铣组合机床设计(全套优秀毕业设计含CAD图纸、说明书)
  9. 计算机win10开机音乐,win10系统电脑开机总是自动播放音乐的恢复步骤
  10. Spring核心AOP(面向切面编程)总结