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

这里要用到一些面向对象的基本知识

目录

7-1 伪随机数

输入格式:

输出格式:

输入样例:

输出样例:

7-2 jmu-Java-03面向对象基础-01-构造方法与toString 

1.编写无参构造函数:

2.编写有参构造函数

3.覆盖toString函数:

4.对每个属性生成setter/getter方法

5.main方法中

输入样例:

输出样例:

7-3 jmu-Java-03面向对象基础-02-构造方法与初始化块 

1.定义一个Person类

2.定义类的初始化块

3.编写静态初始化块

4.编写main方法

思考

输入样例:

输出样例:

7-4 复数类的定义 

输入格式:

输出格式:

输入样例:

输出样例:

7-5 jmu-Java-01入门-开根号 

输入格式:

输出格式:

输入样例:

输出样例:

7-6 jmu-Java-01入门-取数字浮点数 

输入格式:

输出格式:

输入样例:

输出样例:

7-7 日期类设计 

输入格式:

输出格式:

输入样例1:

输出样例1:

输入样例2:

输出样例2:

输入样例3:

输出样例3:

输入样例4:

输出样例4:

7-8 jmu-Java-03面向对象基础-03-形状 

1. 定义长方形类与圆形类Circle

2. main方法

输入样例:

输出样例:

7-9 jmu-Java-02基本语法-01-综合小测验 

输入格式:

输出格式:

7-10 jmu-Java-02基本语法-04-动态数组 

输出格式说明

输入样例:

输出样例:

7-11 jmu-Java-02基本语法-07-大整数相加 

输入格式

输入样例:

输出样例:

7-12 jmu-Java-03面向对象基础-05-覆盖 

1. 新建PersonOverride类

2. main方法

输入样例:

输出样例:


7-1 伪随机数

在java.util这个包里面提供了一个Random的类,我们可以新建一个Random的对象来产生随机数,他可以产生随机整数、随机float、随机double,随机long。Random的对象有两种构建方式:带种子和不带种子。不带种子的方式将会返回随机的数字,每次运行结果不一样。无论程序运行多少次,带种子方式构建的Random对象会返回一样的结果。

请编写程序,使用第一种方式构建Random对象,并完成下面输入输出要求。

输入格式:

在一行中输入3个不超过10000的正整数n,m,k。

输出格式:

在一行中输出以k为种子建立的Random对象产生的第n个0到m-1之间的伪随机数。

输入样例:

10 100 1000

输出样例:

50
import java.util.*;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.StreamTokenizer;
import java.lang.*;public class Main {static PrintWriter out = new PrintWriter(System.out);static StreamTokenizer in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));static Scanner cin = new Scanner(System.in);static Random rnd = new Random();static void solve() throws IOException{int n,m,k;n = cin.nextInt();m = cin.nextInt();k = cin.nextInt();rnd.setSeed(k);int res = 0;for(int i=0;i<n;i++){res = rnd.nextInt(m); }out.println(res);}public static void main(String [] args) throws IOException{solve();out.flush();}
}

7-2 jmu-Java-03面向对象基础-01-构造方法与toString 

定义一个有关人的Person类,内含属性:
String nameint ageboolean genderint id,所有的变量必须为私有(private)。
注意:属性顺序请严格按照上述顺序依次出现。

1.编写无参构造函数:

  • 打印"This is constructor"。
  • 将name,age,gender,id按照name,age,gender,id格式输出

2.编写有参构造函数

依次对name,age,gender赋值。

3.覆盖toString函数:

按照格式:类名 [name=, age=, gender=, id=]输出。建议使用Eclipse自动生成.

4.对每个属性生成setter/getter方法

5.main方法中

  • 首先从屏幕读取n,代表要创建的对象个数。
  • 然后输入n行name age gender , 调用上面2编写的有参构造函数新建对象。
  • 然后将刚才创建的所有对象逆序输出。
  • 接下来使用无参构造函数新建一个Person对象,并直接打印该对象。

输入样例:

3
a 11 false
b 12 true
c 10 false

输出样例:

Person [name=c, age=10, gender=false, id=0]
Person [name=b, age=12, gender=true, id=0]
Person [name=a, age=11, gender=false, id=0]
This is constructor
null,0,false,0
Person [name=null, age=0, gender=false, id=0]
import java.util.*;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.StreamTokenizer;
import java.lang.*;class Person{private String name = null;private int age = 0;private boolean gender = false;private int id = 0; Person(){System.out.println("This is constructor");System.out.printf("%s,%d,%b,%d%n",name,age,gender,id);}Person(String _name,int _age,boolean _gender){this.name = _name;this.age = _age;this.gender = _gender;}public String toString(){System.out.println("Person [name="+this.name+", age="+this.age+", gender="+this.gender+", id="+this.id+"]");return "love jyy three thousand times";}
}public class Main {static PrintWriter out = new PrintWriter(System.out);static Scanner in = new Scanner(System.in);static void solve() throws IOException{int n = in.nextInt();Person ps[] = new Person[n];for(int i=0;i<n;i++){String name = in.next();int age = in.nextInt();boolean gender = in.nextBoolean();ps[i] = new Person(name,age,gender);}for(int i=n-1;i>=0;i--){ps[i].toString();}Person a = new Person();a.toString();}public static void main(String [] args) throws IOException{solve();}
}

7-3 jmu-Java-03面向对象基础-02-构造方法与初始化块 

1.定义一个Person类

属性:String nameboolean genderint ageint id ,所有的变量必须为私有(private)。
无参构造函数:Person()功能:打印This is constructor 。
有参构造函数:Person(name, gender, age)  ,功能:给属性赋值。
建议:使用Eclipse自动生成toString方法

2.定义类的初始化块

为Person类加入初始化块,在初始化块中对id属性赋值,并且要保证每次的值比上次创建的对象的值+1。然后在下一行打印This is initialization block, id is ... 其中...是id的值。
提示:可为Person类定义一个static属性来记录所创建的对象个数。

3.编写静态初始化块

打印This is static initialization block

4.编写main方法

  • 首先输入n,代表要创建的对象数量。
  • 然后从控制台分别读取n行的name age gender, 并调用有参构造函数Person(name, age, gender)新建对象 。
  • 将创建好的n个对象逆序输出(即输出toString()方法)。
  • 使用无参构造函数新建一个Person对象,然后直接打印该对象。

思考

初始化类与对象有几种方法,构造函数、初始化块、静态初始化块。这三种方法执行的先后顺序是什么?各执行几次。

输入样例:

3
a 11 false
b 12 true
c 10 false

输出样例:

This is static initialization block
This is initialization block, id is 0
This is initialization block, id is 1
This is initialization block, id is 2
Person [name=c, age=10, gender=false, id=2]
Person [name=b, age=12, gender=true, id=1]
Person [name=a, age=11, gender=false, id=0]
This is initialization block, id is 3
This is constructor
null,0,false,3
Person [name=null, age=0, gender=false, id=3]
import java.util.*;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.StreamTokenizer;
import java.lang.*;class Person{private String name = null;private int age = 0;private boolean gender = false;private int id = 0; private static int flag = 0;Person(){System.out.println("This is constructor");System.out.printf("%s,%d,%b,%d%n",name,age,gender,id);}Person(String _name,int _age,boolean _gender){this.name = _name;this.age = _age;this.gender = _gender;}public String toString(){System.out.println("Person [name="+this.name+", age="+this.age+", gender="+this.gender+", id="+this.id+"]");return "love jyy three thousand times";}{id = flag++;System.out.println("This is initialization block, id is " + id);}static{System.out.println("This is static initialization block");}
}public class Main {static Scanner in = new Scanner(System.in);static void solve() throws IOException{int n = in.nextInt();Person ps[] = new Person[n];for(int i=0;i<n;i++){String name = in.next();int age = in.nextInt();boolean gender = in.nextBoolean();ps[i] = new Person(name,age,gender);}for(int i=n-1;i>=0;i--){ps[i].toString();}Person a = new Person();a.toString();}public static void main(String [] args) throws IOException{solve();}
}

7-4 复数类的定义 

编写一个复数类,可以进行复数加法和减法运算。编写一个包含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.*;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.StreamTokenizer;
import java.lang.*;class Complex{private double real = 0;private double imag = 0;public void setRealPart(double _real){this.real = _real;}public void setImaginaryPart(double _imag){this.imag = _imag;}public Complex add(Complex a){Complex tmp = new Complex();tmp.real = this.real + a.real;tmp.imag = this.imag + a.imag; return tmp;}public Complex sub(Complex a){Complex tmp = new Complex();tmp.real = this.real - a.real;tmp.imag = this.imag - a.imag; return tmp;}public String toString(){if(this.real == 0 && this.imag == 0){return "0";}else if(this.real == 0 ){return this.imag + "i";}else if(this.imag == 0){return this.real+"";}else if(this.imag > 0){return this.real + "+" + this.imag + "i";}else{return this.real + "" + this.imag + "i";}}
} public class Main {static Scanner in = new Scanner(System.in);static void solve() throws IOException{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));}public static void main(String [] args) throws IOException{solve();}
}

7-5 jmu-Java-01入门-开根号 

使用逐步逼近法对给定数值x求开根号。

逐步逼近法说明:从0开始逐步累加步长值。

步长=0.0001,epsilon(误差)=0.0001

循环继续的条件:

平方值<x 且 |x-平方值| > epsilon

###说明与参考

  1. 数值输出保留6位小数,使用System.out.printf("%.6f\n")
  2. 求平方,参考Math.pow函数。
  3. 输入值<0时,返回Double.NaN

输入格式:

任意数值

输出格式:

对每一组输入,在一行中输出其开根号。保留6位小数

输入样例:

-1
0
0.5
0.36
1
6
100
131

输出样例:

NaN
0.000000
0.707100
0.600000
1.000000
2.449500
10.000000
11.445600
import java.util.*;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.StreamTokenizer;
import java.lang.*;class sqrt{private double pre;public void setPre(double _pre){this.pre = _pre;}public double cal(){double res = 0;if(this.pre < 0){return -1;}while(true){if(res * res >= this.pre || Math.abs(this.pre - res*res) <0.0001){break;}res += 0.0001;} return res;}} public class Main {static Scanner in = new Scanner(System.in);static void solve() throws IOException{while(true){double num = in.nextDouble();sqrt t = new sqrt();t.setPre(num);Double res = t.cal();if(res == -1){System.out.println("NaN");}else{System.out.printf("%.6f\n",res);}}}public static void main(String [] args) throws IOException{solve();}
}

7-6 jmu-Java-01入门-取数字浮点数 

本题目要求读入若干以回车结束的字符串表示的整数或者浮点数,然后将每个数中的所有数字全部加总求和。

输入格式:

每行一个整数或者浮点数。保证在浮点数范围内。

输出格式:

整数或者浮点数中的数字之和。题目保证和在整型范围内。

输入样例:

-123.01
234

输出样例:

7
9
import java.util.*;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.StreamTokenizer;
import java.lang.*;public class Main {static Scanner in = new Scanner(System.in);static void solve() throws IOException{while(true){String s = in.nextLine();int res = 0;for(int i=0;i<s.length();i++){if(s.charAt(i)>='0' && s.charAt(i)<='9'){res += (int)(s.charAt(i) - '0');}}System.out.println(res);}}public static void main(String [] args) throws IOException{solve();}
}

7-7 日期类设计 

参考题目3和日期相关的程序,设计一个类DateUtil,该类有三个私有属性year、month、day(均为整型数),其中,year∈[1820,2020] ,month∈[1,12] ,day∈[1,31] , 除了创建该类的构造方法、属性的getter及setter方法外,需要编写如下方法:

public boolean checkInputValidity();//检测输入的年、月、日是否合法
public boolean isLeapYear(int year);//判断year是否为闰年
public DateUtil getNextNDays(int n);//取得year-month-day的下n天日期
public DateUtil getPreviousNDays(int n);//取得year-month-day的前n天日期
public boolean compareDates(DateUtil date);//比较当前日期与date的大小(先后)
public boolean equalTwoDates(DateUtil date);//判断两个日期是否相等
public int getDaysofDates(DateUtil date);//求当前日期与date之间相差的天数
public String showDate();//以“year-month-day”格式返回日期值

应用程序共测试三个功能:

  1. 求下n天
  2. 求前n天
  3. 求两个日期相差的天数

注意:严禁使用Java中提供的任何与日期相关的类与方法,并提交完整源码,包括主类及方法(已提供,不需修改)

程序主方法如下:

import java.util.Scanner;public class Main {public static void main(String[] args) {Scanner input = new Scanner(System.in);int year = 0;int month = 0;int day = 0;int choice = input.nextInt();if (choice == 1) { // test getNextNDays methodint m = 0;year = Integer.parseInt(input.next());month = Integer.parseInt(input.next());day = Integer.parseInt(input.next());DateUtil date = new DateUtil(year, month, day);if (!date.checkInputValidity()) {System.out.println("Wrong Format");System.exit(0);}m = input.nextInt();if (m < 0) {System.out.println("Wrong Format");System.exit(0);}System.out.print(date.getYear() + "-" + date.getMonth() + "-" + date.getDay() + " next " + m + " days is:");System.out.println(date.getNextNDays(m).showDate());} else if (choice == 2) { // test getPreviousNDays methodint n = 0;year = Integer.parseInt(input.next());month = Integer.parseInt(input.next());day = Integer.parseInt(input.next());DateUtil date = new DateUtil(year, month, day);if (!date.checkInputValidity()) {System.out.println("Wrong Format");System.exit(0);}n = input.nextInt();if (n < 0) {System.out.println("Wrong Format");System.exit(0);}System.out.print(date.getYear() + "-" + date.getMonth() + "-" + date.getDay() + " previous " + n + " days is:");System.out.println(date.getPreviousNDays(n).showDate());} else if (choice == 3) {    //test getDaysofDates methodyear = Integer.parseInt(input.next());month = Integer.parseInt(input.next());day = Integer.parseInt(input.next());int anotherYear = Integer.parseInt(input.next());int anotherMonth = Integer.parseInt(input.next());int anotherDay = Integer.parseInt(input.next());DateUtil fromDate = new DateUtil(year, month, day);DateUtil toDate = new DateUtil(anotherYear, anotherMonth, anotherDay);if (fromDate.checkInputValidity() && toDate.checkInputValidity()) {System.out.println("The days between " + fromDate.showDate() + " and " + toDate.showDate() + " are:"+ fromDate.getDaysofDates(toDate));} else {System.out.println("Wrong Format");System.exit(0);}}else{System.out.println("Wrong Format");System.exit(0);}        }
}

输入格式:

有三种输入方式(以输入的第一个数字划分[1,3]):

  • 1 year month day n //测试输入日期的下n天
  • 2 year month day n //测试输入日期的前n天
  • 3 year1 month1 day1 year2 month2 day2 //测试两个日期之间相差的天数

输出格式:

  • 当输入有误时,输出格式如下:
    Wrong Format
  • 当第一个数字为1且输入均有效,输出格式如下:
    year1-month1-day1 next n days is:year2-month2-day2
    
  • 当第一个数字为2且输入均有效,输出格式如下:
    year1-month1-day1 previous n days is:year2-month2-day2
    
  • 当第一个数字为3且输入均有效,输出格式如下:
    The days between year1-month1-day1 and year2-month2-day2 are:值
    

输入样例1:

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

3 2014 2 14 2020 6 14

输出样例1:

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

The days between 2014-2-14 and 2020-6-14 are:2312

输入样例2:

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

2 1834 2 17 7821

输出样例2:

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

1834-2-17 previous 7821 days is:1812-9-19

输入样例3:

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

1 1999 3 28 6543

输出样例3:

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

1999-3-28 next 6543 days is:2017-2-24

输入样例4:

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

0 2000 5 12 30

输出样例4:

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

Wrong Format
import java.util.Scanner;class DateUtil{private int year;private int month;private int day;public DateUtil(){}public DateUtil(int _year,int _month,int _day){this.year = _year;this.month = _month;this.day = _day;}public int getDay(){return this.day;}public int getYear(){return this.year;}public int getMonth(){return this.month;}public boolean checkInputValidity(){if(year <= 2020 && year >= 1820 && month >= 1 && month <= 12 && day >= 1 && day <= 31){if(day <= daysInMonth(year,month)){return true;}}return false;}public boolean isLeapYear(int _year){if(_year % 4 ==0 && _year % 100 != 0 || _year % 400 ==0){return true;}return false;}public DateUtil getNextNDays(int n){int _day = day;int _month = month;int _year = year;int[] daysInMonth = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};if (isLeapYear(_year)) {daysInMonth[2] = 29;}for (int i = 0; i < n; i++) {_day++;if (_day > daysInMonth[_month]) {_day = 1;_month++;if (_month > 12) {_month = 1;_year++;daysInMonth[2] = isLeapYear(_year) ? 29 : 28;}}}// _day += n;// while (_day > daysInMonth[_month]) {//     _day -= daysInMonth[_month];//     _month++;//     if (_month > 12) {//         _month = 1;//         _year++;//         daysInMonth[2] = isLeapYear(_year) ? 29 : 28;//     }// }DateUtil res = new DateUtil(_year,_month,_day);return res;}public DateUtil getPreviousNDays(int n){int _day = day;int _month = month;int _year = year;int[] daysInMonth = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};if (isLeapYear(_year)) {daysInMonth[2] = 29;}for (int i = 0; i < n; i++) {_day--;if (_day == 0) {_month--;if (_month == 0) {_month = 12;_year--;daysInMonth[2] = isLeapYear(_year) ? 29 : 28;}_day = daysInMonth[_month];}}// _day -= n;// while (_day < 1) {//     _month --;//     if (_month < 1) {//         _month = 12;//         _year--;//         daysInMonth[2] = isLeapYear(_year) ? 29 : 28;//     }//     _day += daysInMonth[_month];// }DateUtil res = new DateUtil(_year,_month,_day);return res;}public int daysInMonth(int _year, int _month) {int[] daysInMonth = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};if (isLeapYear(_year) && _month == 2) {return 29;}return daysInMonth[_month]; }public int getDaysofDates(DateUtil date){int year1 = this.year;int year2 = date.year;int day1 = this.day;int day2 = date.day;int month1 = this.month;int month2 = date.month;if (year1 > year2 || (year1 == year2 && month1 > month2) || (year1 == year2 && month1 == month2 && day1 > day2)) {int tempYear = year1;int tempMonth = month1;int tempDay = day1;year1 = year2;month1 = month2;day1 = day2;year2 = tempYear;month2 = tempMonth;day2 = tempDay;}int daysDifference = 0;for (int year = year1; year < year2; year++) {daysDifference += isLeapYear(year) ? 366 : 365;}daysDifference += dayOfYear(year2, month2, day2);daysDifference -= dayOfYear(year1, month1, day1);return daysDifference;}public int dayOfYear(int _year, int _month, int _day) {int[] daysInMonth = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};if (isLeapYear(_year)) {daysInMonth[2] = 29;}int dayOfYear = 0;for (int i = 1; i < _month; i++) {dayOfYear += daysInMonth[i];}dayOfYear += _day;return dayOfYear;}public String showDate(){return year + "-" + month + "-" + day;}}public class Main {public static void main(String[] args) {Scanner input = new Scanner(System.in);int year = 0;int month = 0;int day = 0;int choice = input.nextInt();if (choice == 1) { // test getNextNDays methodint m = 0;year = Integer.parseInt(input.next());month = Integer.parseInt(input.next());day = Integer.parseInt(input.next());DateUtil date = new DateUtil(year, month, day);if (!date.checkInputValidity()) {System.out.println("Wrong Format");System.exit(0);}m = input.nextInt();if (m < 0) {System.out.println("Wrong Format");System.exit(0);}System.out.print(date.getYear() + "-" + date.getMonth() + "-" + date.getDay() + " next " + m + " days is:");System.out.println(date.getNextNDays(m).showDate());} else if (choice == 2) { // test getPreviousNDays methodint n = 0;year = Integer.parseInt(input.next());month = Integer.parseInt(input.next());day = Integer.parseInt(input.next());DateUtil date = new DateUtil(year, month, day);if (!date.checkInputValidity()) {System.out.println("Wrong Format");System.exit(0);}n = input.nextInt();if (n < 0) {System.out.println("Wrong Format");System.exit(0);}System.out.print(date.getYear() + "-" + date.getMonth() + "-" + date.getDay() + " previous " + n + " days is:");System.out.println(date.getPreviousNDays(n).showDate());} else if (choice == 3) {    //test getDaysofDates methodyear = Integer.parseInt(input.next());month = Integer.parseInt(input.next());day = Integer.parseInt(input.next());int anotherYear = Integer.parseInt(input.next());int anotherMonth = Integer.parseInt(input.next());int anotherDay = Integer.parseInt(input.next());DateUtil fromDate = new DateUtil(year, month, day);DateUtil toDate = new DateUtil(anotherYear, anotherMonth, anotherDay);if (fromDate.checkInputValidity() && toDate.checkInputValidity()) {System.out.println("The days between " + fromDate.showDate() + " and " + toDate.showDate() + " are:"+ fromDate.getDaysofDates(toDate));} else {System.out.println("Wrong Format");System.exit(0);}}else{System.out.println("Wrong Format");System.exit(0);}        }
}

7-8 jmu-Java-03面向对象基础-03-形状 

1. 定义长方形类与圆形类Circle

长方形类-类名:Rectangleprivate属性:int width,length
圆形类-类名:Circleprivate属性:int radius

编写构造函数:
带参构造函数:Rectangle(width, length),Circle(radius)

编写方法:
public int getPerimeter(),求周长。
public int getArea(),求面积。
toString方法,使用Eclipse自动生成。

注意:

  1. 计算圆形的面积与周长,使用Math.PI
  2. 求周长和面积时,应先计算出其值(带小数位),然后强制转换为int再返回。

2. main方法

  • 输入2行长与宽,创建两个Rectangle对象放入相应的数组。
  • 输入2行半径,创建两个Circle对象放入相应的数组。
  • 输出1:上面2个数组中的所有对象的周长加总。
  • 输出2:上面2个数组中的所有对象的面积加总。
  • 最后需使用Arrays.deepToString分别输出上面建立的Rectangle数组与Circle数组

思考:如果初次做该题会发现代码冗余严重。使用继承、多态思想可以大幅简化上述代码。

输入样例:

1 2
3 4
7
1

输出样例:

69
170
[Rectangle [width=1, length=2], Rectangle [width=3, length=4]]
[Circle [radius=7], Circle [radius=1]]
import java.util.*;class Rectangle{private int width;private int length;public Rectangle(){}public Rectangle(int _width,int _length){this.length = _length;this.width = _width;}public int getPerimeter(){return (length + width)*2;}public int getArea(){return length * width;}public String toString(){return "Rectangle "+ "[width=" + this.width +", length=" + this.length +"]"; }
}class Circle{private int radius;public Circle(){}public Circle(int _radius){this.radius = _radius;}public int getPerimeter(){double res = radius * 2 * Math.PI; return (int) res;}public int getArea(){double res = radius * radius * Math.PI;return (int) res;}public String toString(){return "Circle " + "[radius=" + this.radius + "]"; }
}public class Main {public static void main(String[] args) {Scanner in = new Scanner(System.in);int a,b;Rectangle r[] = new Rectangle[2];a = in.nextInt();b = in.nextInt();r[0] = new Rectangle(a,b);a = in.nextInt();b = in.nextInt();r[1] = new Rectangle(a,b);Circle c[] = new Circle[2];int radius = in.nextInt();c[0] = new Circle(radius);radius = in.nextInt();c[1] = new Circle(radius);int peri = r[0].getPerimeter() + r[1].getPerimeter() + c[0].getPerimeter() + c[1].getPerimeter();int area = r[0].getArea() + r[1].getArea() + c[0].getArea() + c[1].getArea();System.out.println(peri); System.out.println(area); System.out.println(Arrays.deepToString(r));System.out.println(Arrays.deepToString(c));}
}

7-9 jmu-Java-02基本语法-01-综合小测验 

运行程序后可以输入4个选项,分别为:fib,sort,search,getBirthDate

fib:根据输入n,打印斐波那契数列。比如输入:3,输出:1 1 2

sort:输入一串数字,然后进行排序并输出,注意数组元素输出的格式为使用[ ]包括。提示:可直接使用函数Arrays相关方法处理输出。

search:如果找到返回所找到的位置,如果没找到,返回-1。提示: 可以先对数组排序,然后使用Arrays相关函数进行查找。

getBirthDate:输入n个身份证,然后把输入的n个身份号的年月日抽取出来,按年-月-日格式输出。

当输入不是这几个字符串(fib,sort,search,getBirthDate)的时候,显示exit并退出程序。

注意: 在处理输入的时候,尽量只使用Scanner的nextLine()方法接收输入,不要将nextLine()与其它next方法混用,否则可能会出现行尾回车换行未处理影响下次输入的情况。

参考:jdk文档的Arrays,String

输入格式:

fib
3
sort
-1 10 3 2 5
search
-1
search
0
getBirthDate
1
330226196605054190
e

输出格式:

1 1 2
[-1, 2, 3, 5, 10]
0
-1
1966-05-05
exit
import java.util.*;public class Main {static Scanner in = new Scanner(System.in);static int num[] = new int[1];public static void sort(){String numString[] = in.nextLine().split(" ");num = new int[numString.length];for(int i=0; i<numString.length;i++){num[i] = Integer.valueOf(numString[i]);}Arrays.sort(num);System.out.println(Arrays.toString(num));}public static void fib(){int n = in.nextInt();in.nextLine();int pre = 0;int now = 1;for(int i=0;i<n-1;i++){System.out.print(now + " ");int tmp = now;now += pre;pre = tmp;}System.out.println(now);}public static void getBirthDate(){int n = in.nextInt();in.nextLine();String s[] = new String[n];for(int i=0;i<n;i++){s[i] = in.nextLine();}for(int i=0;i<n;i++){System.out.println(s[i].substring(6,10) + "-" + s[i].substring(10,12) + "-" + s[i].substring(12,14));}}public static void search(){int n = in.nextInt();in.nextLine();int flag = 0;for (int i = 0; i < num.length; i++) {//System.out.println(num[i]);if (num[i] == n) {System.out.println(i);flag = 1;break;}}if (flag == 0){System.out.println(-1);}}public static void main(String[] args) {while(true){String op = in.nextLine();if(op.equals("sort")){sort();}else if(op.equals("search")){search();}else if(op.equals("fib")){fib();}else if(op.equals("getBirthDate")){getBirthDate();}else{System.out.println("exit");break;}}}
}

7-10 jmu-Java-02基本语法-04-动态数组 

根据输入的n,打印n行乘法口诀表。
需要使用二维字符串数组存储乘法口诀表的每一项,比如存放1*1=1.
为了保证程序中使用了二维数组,需在打印完乘法口诀表后使用Arrays.deepToString打印二维数组中的内容。

提醒:格式化输出可使用String.format或者System.out.printf

输出格式说明

  1. 每行末尾无空格。
  2. 每一项表达式之间(从第1个表达式的第1个字符算起到下一个表达式的首字符之间),共有包含7个字符。如2*1=2 2*2=4从第1个2开始到第二项``2*2=4`首字母之间,总共有7个字符(包含空格,此例中包含2个空格)。

输入样例:

2
5

输出样例:

1*1=1
2*1=2  2*2=4
[[1*1=1], [2*1=2, 2*2=4]]
1*1=1
2*1=2  2*2=4
3*1=3  3*2=6  3*3=9
4*1=4  4*2=8  4*3=12 4*4=16
5*1=5  5*2=10 5*3=15 5*4=20 5*5=25
[[1*1=1], [2*1=2, 2*2=4], [3*1=3, 3*2=6, 3*3=9], [4*1=4, 4*2=8, 4*3=12, 4*4=16], [5*1=5, 5*2=10, 5*3=15, 5*4=20, 5*5=25]]
import java.util.*;public class Main {static Scanner in = new Scanner(System.in);public static void main(String[] args) {while(in.hasNextInt()) {int n = in.nextInt();String[][] arr = new String[n][];for(int i=0;i<n;i++) {arr[i] = new String[i+1];for(int j = 0;j < i+1;j++) {arr[i][j] = (i+1)+"*"+(j+1)+"="+(i+1)*(j+1);if(j<i){System.out.printf("%-7s",arr[i][j]);}else if(j==i){System.out.printf("%s",arr[i][j]);}}System.out.println();}System.out.println(Arrays.deepToString(arr));}}
}

7-11 jmu-Java-02基本语法-07-大整数相加 

有若干大整数,需要对其进行求和操作。

输入格式

每行输入一个字符串代表一个大整数,连续输入若干行,当某行字符为eE时退出。

输入样例:

42846280183517070527831839425882145521227251250327
55121603546981200581762165212827652751691296897789
e

输出样例:

97967883730498271109594004638709798272918548148116
import java.math.*;
import java.util.*;public class Main {static Scanner in = new Scanner(System.in);public static void main(String[] args) {BigInteger res = new BigInteger("0");while(in.hasNext()) {String s = in.next();if(s.equals("e") || s.equals("E")){break;}BigInteger tmp = new BigInteger(s);res=res.add(tmp);}System.out.println(res);}
}

7-12 jmu-Java-03面向对象基础-05-覆盖 

Java每个对象都继承自Object,都有equals、toString等方法。
现在需要定义PersonOverride类并覆盖其toStringequals方法。

1. 新建PersonOverride

a. 属性String nameint ageboolean gender,所有的变量必须为私有(private)。

b. 有参构造方法,参数为name, age, gender

c. 无参构造方法,使用this(name, age,gender)调用有参构造方法。参数值分别为"default",1,true

d.toString()方法返回格式为:name-age-gender

e. equals方法需比较name、age、gender,这三者内容都相同,才返回true.

2. main方法

2.1 输入n1,使用无参构造方法创建n1个对象,放入数组persons1。
2.2 输入n2,然后指定name age gender。每创建一个对象都使用equals方法比较该对象是否已经在数组中存在,如果不存在,才将该对象放入数组persons2。
2.3 输出persons1数组中的所有对象
2.4 输出persons2数组中的所有对象
2.5 输出persons2中实际包含的对象的数量
2.5 使用System.out.println(Arrays.toString(PersonOverride.class.getConstructors()));输出PersonOverride的所有构造方法。

提示:使用ArrayList代替数组大幅复简化代码,请尝试重构你的代码。

输入样例:

1
3
zhang 10 true
zhang 10 true
zhang 10 false

输出样例:

default-1-true
zhang-10-true
zhang-10-false
2
[public PersonOverride(), public PersonOverride(java.lang.String,int,boolean)]
import java.math.*;
import java.util.*;class PersonOverride{private int age;private String name;private boolean gender;public PersonOverride(){this("default",1,true);}public PersonOverride(String _name,int _age,boolean _gender){this.name = _name;this.age = _age;this.gender = _gender;}public String toString(){return this.name + "-" + this.age + "-" + this.gender;}public boolean equals(PersonOverride a){return this.name.equals(a.name) && this.age == a.age && this.gender == a.gender;}}
public class Main {static Scanner in = new Scanner(System.in);static int num[] = new int[1];public static void main(String[] args) {int n1 = in.nextInt();ArrayList<PersonOverride> person1 = new ArrayList<PersonOverride>();for(int i=0;i<n1;i++){person1.add(new PersonOverride());}int n2 = in.nextInt();ArrayList<PersonOverride> person2 = new ArrayList<PersonOverride>();String name = in.next();int age = in.nextInt();boolean gender = in.nextBoolean();PersonOverride tmp = new PersonOverride(name,age,gender);person2.add(tmp);for(int i=1;i<n2;i++){name = in.next();age = in.nextInt();gender = in.nextBoolean();tmp = new PersonOverride(name,age,gender);int flag = 1;for(int j=0;j<person2.size();j++){if(tmp.equals(person2.get(j))){flag = 0;}}if(flag == 1){person2.add(tmp);}}for(int i=0;i<n1;i++){System.out.println(person1.get(i).toString());}for(int i=0;i<person2.size();i++){System.out.println(person2.get(i).toString());}System.out.println(person2.size());System.out.println(Arrays.toString(PersonOverride.class.getConstructors()));}
}

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

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

相关文章

基于SSM的汽车维修管理系统

文章目录 项目介绍主要功能截图:部分代码展示设计总结项目获取方式🍅 作者主页:超级无敌暴龙战士塔塔开 🍅 简介:Java领域优质创作者🏆、 简历模板、学习资料、面试题库【关注我,都给你】 🍅文末获取源码联系🍅 项目介绍 基于SSM的汽车维修管理系统,java项目。 …

解决找不到vcruntime140.dll,无法继续执行代码方法

在计算机使用过程中&#xff0c;我们经常会遇到一些错误提示&#xff0c;其中之一就是“找不到vcruntime140.dll”。这个错误通常发生在运行某些程序或游戏时&#xff0c;它会导致程序无法正常启动或运行。那么&#xff0c;找不到vcruntime140.dll&#xff0c;无法继续执行代码…

word中批注内容显示设置

在修改他人word时&#xff0c;有时候保存为pdf需要有选择性的显示&#xff0c;如下图&#xff0c;原始修改方式包括三种&#xff1a;批注、格式修改、删除添加&#xff0c;如下图所示&#xff1a; 有时候不想要格式设置说明&#xff0c;则只需要进行在审阅--显示标志--不勾选设…

【Java 进阶篇】解决Java Web应用中请求参数中文乱码问题

在Java Web应用开发中&#xff0c;处理请求参数时经常会遇到中文乱码的问题。当浏览器向服务器发送包含中文字符的请求参数时&#xff0c;如果不正确处理&#xff0c;可能会导致乱码问题&#xff0c;使得参数无法正确解析和显示。本文将详细探讨Java Web应用中请求参数中文乱码…

qt高精度定时器的使用停止线程应用

##线程停止 //线程停止应用 public: explicit WorkerThread(QObject *parent 0) :QThread(parent), m_bStopped(false){qDebug() << "Worker Thread : " << QThread::currentThreadId();}~WorkerThread(){stop();quit();wait();}void stop() {qDebug()…

数据可视化的常见工具

Tableau: Tableau是一种流行的商业数据可视化工具&#xff0c;可以连接各种数据源&#xff0c;创建交互式仪表板和报告。它提供了强大的图表和图形功能。 Power BI: Power BI是微软的数据分析和可视化工具&#xff0c;与Microsoft生态系统紧密集成。它支持从多个数据源创建可视…

共用体开发案例

有若干个人员的数据,其中有学生和教师。学生的数据中包括:姓名、号码性别、职业、班级。教师的数据包括:姓名、号码、性别、职业、职务。要求用同一个表格来处理。 #include <stdio.h>struct Person {char name[32];int age;char zhiYe;char addr[32];union {int class;…

JDBC与MySql数据库

一、系统开发前的环境准备 1.下载Mysql 下载地址&#xff1a;https://dev.mysql.com/downloads/mysql/ 文件解压缩到本地 在此路径下新增my.ini文件以及新建data文件夹 编辑my.ini文件 配置环境变量 注意是编辑系统变量的Path 以管理员身份运行cmd 输入命令&#xff1a…

VDA到Excel方案介绍之自定义邮件接收主题

VDA标准是德国汽车工业协会&#xff08;Verband der Automobilindustrie&#xff0c;简称VDA&#xff09;制定的一系列汽车行业标准。这些标准包括了汽车生产、质量管理、供应链管理、环境保护、安全性能等方面的规范和指南。VDA标准通常被德国和国际上的汽车制造商采用&#x…

【机器学习】sklearn特征值选取与处理

sklearn特征值选取与处理 文章目录 sklearn特征值选取与处理1. 调用数据集与数据集的划分2. 字典特征选取3. 英文文本特征值选取4. 中文特征值选取5. 中文分词文本特征抽取6. TfidfVectorizer特征抽取7. 归一化处理8. 标准化处理9. 过滤低方差特征10. 主成分分析11. 案例&#…

制作自己的前端组件库并上传到npm上

最近实现了自己的一个前端组件库demo&#xff0c;目前只上传了几个小组件。话不多说&#xff0c;上图&#xff1a; 我分了三个项目&#xff1a;yt-ui组件库、使用文档、demo。线上地址如下&#xff1a; [yt-ui组件库](mhfwork/yt-ui - npm) [组件库使用文档](介绍 | mhfwork/y…

docker应用部署---Tomcat的部署配置

1. 搜索tomcat镜像 docker search tomcat2. 拉取tomcat镜像 docker pull tomcat3. 创建容器&#xff0c;设置端口映射、目录映射 # 在/root目录下创建tomcat目录用于存储tomcat数据信息 mkdir ~/tomcat cd ~/tomcatdocker run -id --namec_tomcat \ -p 8080:8080 \ -v $PWD:…

拓扑排序详解

拓扑排序 如果说最短路径是有环图的应用&#xff0c;那么拓扑排序就是无环图的应用。 拓扑排序介绍 我们会把施工过程、生产流程、软件开发、教学安排等都当成- -个项目工程来对待&#xff0c;所有的工程都可分为若干个“活动”的子工程。例如下图是我这非专业人士绘制的一张…

bbr 流相互作用图示

类似 AIMD 收敛图&#xff0c;给出 bbr 的对应图示&#xff1a; bbr 多流相互作用非常复杂&#xff0c;和右下角的 AIMD 相比&#xff0c;毫无美感&#xff0c;但是看一眼左下角的 bbr 单流情况&#xff0c;又过于简陋&#xff0c;而 bbr 的核心就基于这简陋的假设。 浙江温…

ChatGPT从入门到精通

目录 什么是ChatGPT&#xff1f;ChatGPT能帮我干什么&#xff1f;标题在哪里可以使用ChatGPT&#xff1f;什么是ILoveChatGPT&#xff08;IMYAI&#xff09;&#xff1f;标题如何拥有头像&#xff1f;如何获取更多对话次数&#xff1f;!标题如何提问GPT&#xff1f;如何正确地利…

【黑马程序员】mysql进阶再进阶篇笔记

64. 进阶-锁-介绍(Av765670802,P121) 为了应对不同场景 全局锁-所有表 表计锁 一张表 行级锁 一行数据 65. 进阶-锁-全局锁-介绍(Av765670802,P122) 66. 进阶-锁-全局锁-一致性数据备份(Av765670802,P123) 67. 进阶-锁-表级锁-表锁(Av765670802,P124) 读锁、写锁 68. 进阶…

SSD1306 oled显示屏的驱动SPI接口

有IIC接口 和SPI接口 还有8080,6080接口等 arduino SPI接口 直接使用u8g2库实现 //U8G2_SSD1306_128X64_NONAME_F_4W_SW_SPI u8g2(U8G2_R0, /* clock*/ 13, /* data*/ 11, /* cs*/ 10, /* dc*/ 9, /* reset*/ 8); asrpro(SPI接口按下方修改&#xff0c;IIC接口官方有驱动&…

数据结构OJ题

目录 1.字符串左旋 2.字符串旋转结果 3.旋转数组 4.移除元素 本篇主要是讲解一些OJ题目。 1.字符串左旋 字符串左旋 实现一个函数&#xff0c;可以左旋字符串中的k个字符 例如&#xff1a; ABCD左旋一个字符得到BCDA ABCD左旋两个字符得到CDAB 方法1【暴力求解】 翻转1…

css overflow-x: scroll 滚动不展示/隐藏滚动条 /如何滚动

overflow-x:scroll 实现滚动效果 .scroll{width: 300rpx;height: 100rpx;//超出部分隐藏overflow-x: hidden;//禁止换行white-space: nowrap;//显示滚动条overflow-x: scroll; } 操作滚动条的伪类元素 ::-webkit-scrollbar — 整个滚动条.::-webkit-scrollbar-button — 滚动…

MSQL系列(八) Mysql实战-SQL存储引擎

Mysql实战-SQL存储引擎 前面我们讲解了索引的存储结构&#xff0c;BTree的索引结构&#xff0c;我们一般都知道Mysql的存储引擎有两种&#xff0c;MyISAM和InnoDB,今天我们来详细讲解下Mysql的存储引擎 文章目录 Mysql实战-SQL存储引擎1.存储引擎2.MyISAM的特点3. InnoDB的特…