目录
根据已有类Worker,使用LinkedList编写一个WorkerList类,实现计算所有工人总工资的功能。
编写Student类,使用泛型和集合框架编写StudentList类,实现计算班级平均分的功能。
超市奖票兑换
import java.util.Arrays;//数组类
import java.util.Scanner;
public class Main {
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[] arr = new int[n];
int k1=0,k2=0,f1=0,f2=0,c=0;//k1,k2是数组下标标记,f1,f2是是否找到的旗帜,c是计数器
for (int i = 0; i < n; i++){
arr[i] = sc.nextInt();
}
Arrays.sort(arr);//引用Arrays类,对数组进行排序(升序)
for (int j = 1; j < n; j++){
for (int i = 0; i < j; i++){
if ((arr[i]+1) == arr[j] ){
k1 = i;
f1 = 1;
}
}//比arr[j]小1的数
for (int i = j+1; i < n; i++){
if ((arr[i]-1) == arr[j] ){
k2 = i;
f2 = 1;
}
}//比arr[j]大1的数
//由此构成连续的三个数
if (f1==1&&f2==1){ // 找到了连续的3个数
c++; //计数器加1
f1=f2=0;//旗帜标0
arr[k1]=arr[k2]=arr[j]=0;//重要动作!!!!注意标0,表示奖票已兑换!!
}
}
System.out.print(c);
}
}
回文判断
回文是指正读反读均相同的字符序列,如“abba”和“abdba”均是回文,但“good”不是回文。编写一个程序,判定给定的字符序列是否为回文。
*注:如果输入的不是字母或者数字,请过滤。
可以考虑使用StringBuilder来存储字符串,这样便于后续的处理。*
输入样例:
123**&321
输出样例:
true
知识点:
StringBuilder类的使用,和字符串判断是否为字母和数字的函数。
Character类对字母和数字的判别,和小写化。
代码:
import java.util.Scanner;
public class Main {
public static boolean isPalindrome(String input) {
// 使用StringBuilder来过滤并构建新的字符序列
StringBuilder filtered = new StringBuilder();
// 遍历输入字符串的每一个字符
for (char c : input.toCharArray()) {
// 检查字符是否是字母或数字
if (Character.isLetterOrDigit(c)) {
// 转换为小写并添加到StringBuilder中
filtered.append(Character.toLowerCase(c));
}
}
// 获取过滤后的字符串
String filteredString = filtered.toString();
// 使用双指针法检查回文
int left = 0;
int right = filteredString.length() - 1;
while (left < right) {
if (filteredString.charAt(left) != filteredString.charAt(right)) {
return false; // 不是回文
}
left++;
right--;
}
return true; // 是回文
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String input = scanner.nextLine();
scanner.close();
boolean result = isPalindrome(input);
System.out.println(result ? "true" : "false");
}
}
华氏度转摄氏度
本题要求编写程序,计算华氏温度对应的摄氏温度。计算公式:C=5×(F−32)/9,式中:C表示摄氏温度,F表示华氏温度,输出数据要求为四舍五入取整后整型。
输入样例:
100
输出样例:
38
知识点:
四舍五入的方法有Math.round(), Math.rint(),其内得是浮点型的数,int型的话会自动舍弃小数点。
代码:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
double n = sc.nextInt();
double t = Math.round((n-32)*5/9);
System.out.printf("%.0f", t);
}
}
消费税计算
营业税为消费额的6%,用户输入消费金额,程序计算出营业税,计算结果四舍五入保留小数点两位。当输入金额为负数是,系统输出“Invalid input”。
输入样例:
5
输出样例:
0.30
知识点:
使用BigDecimal类对指定小数位数进行四舍五入。
或者使用以下方法
//注意这里保留两位小数的处理
ibm = (double)Math.round(ibm * 100) / 100;
代码:
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
double n = sc.nextDouble();
if (n < 0) {
System.out.print("Invalid input");
}
else {
BigDecimal bd = new BigDecimal(n*0.06);
bd = bd.setScale(2, RoundingMode.HALF_UP);
System.out.printf("%.2f", bd.doubleValue());
}
}
}
大数相加
在Java语言中,整数相加受到了位数的限制,请实现两个超大整数的加法。
输入样例:
12345678909876543210
98765432101234567890
输出样例:
12345678909876543210+98765432101234567890=111111111011111111100
代码:
package test;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Scanner;
public class Main {
public static String add(String num1, String num2) {
// 反转两个字符串,以便从最低位开始相加
String reversedNum1 = new StringBuilder(num1).reverse().toString();
String reversedNum2 = new StringBuilder(num2).reverse().toString();
int length1 = reversedNum1.length();
int length2 = reversedNum2.length();
int maxLen = Math.max(length1, length2);
int carry = 0; // 进位
StringBuilder result = new StringBuilder();
for (int i = 0; i < maxLen; i++) {
int digit1 = i < length1 ? reversedNum1.charAt(i) - '0' : 0;
int digit2 = i < length2 ? reversedNum2.charAt(i) - '0' : 0;
int sum = digit1 + digit2 + carry;
carry = sum / 10; // 更新进位
result.append(sum % 10);
}
// 如果最后还有进位,需要加到结果中
if (carry > 0) {
result.append(carry);
}
// 将结果反转回来,因为我们是从最低位开始加的
return new StringBuilder(result.toString()).reverse().toString();
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String num1 = sc.nextLine();
String num2 = sc.nextLine();
System.out.println(num1+"+"+num2+"="+ add(num1, num2));
}
}
多线程打印大写字母
(接口)
通过接口方式实现多线程,在主方法中输入N(取值范围在1到26),然后通过线程输出相应个数的大写字母(每个字母后面都有一个半角的空格)。
在这里给出函数被调用进行测试的例子。例如:
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
MyThread mythread=new MyThread(sc.nextInt());
Thread threadone;
threadone = new Thread(mythread);
threadone.start();
sc.close();
}
}
/* 请在这里填写答案 */
ac代码:
class MyThread implements Runnable{
private int count;
public MyThread(int count) {
this.count = count;
}
public void run() {
for (int i = 0; i<count; i++) {
System.out.print((char)('A'+i)+" ");
}
}
}
(继承)
通过继承方式实现多线程,在主方法中输入N(取值范围在1到26),然后通过线程输出相应个数的小写字母(每个字母后面都有一个半角的空格)。
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
ThreadTest mythread;
mythread = new ThreadTest(sc.nextInt());
mythread.start();
sc.close();
}
}
/* 请在这里填写答案 */
AC代码:
class ThreadTest extends Thread {
private int n; // 需要输出的字母个数
// 构造函数,接收需要输出的字母个数
public ThreadTest(int n) {
this.n = n;
}
// 重写run方法,实现线程的执行逻辑
public void run() {
for (int i = 0; i < n; i++) {
System.out.print((char)('A' + i) + " ");
}
System.out.println(); // 输出换行符,以便输出结果更清晰
}
}
分数加减法(类和对象)
编写一个Java程序,实现两个分数的加减法,
输入:
包含多行数据,每行数据是一个字符串,格式是"a/boc/d"。
其中a, b, c, d是一个0-9的整数。o是运算符"+"或者"-"。
输入数据保证合法。
输出:
对于输入数据的每一行输出两个分数的运算结果。
注意结果应符合书写习惯,没有多余的符号、分子、分母,并且化简至最简分数
import java.util.Scanner;
/* 请在这里填写答案 */
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while (sc.hasNext()) {
String str = sc.next();
char[] ch = str.toCharArray();
int a = ch[0] - '0';
int b = ch[2] - '0';
int c = ch[4] - '0';
int d = ch[6] - '0';
Fs fs1 = new Fs(a, b);
Fs fs2 = new Fs(c, d);
Fs result = null;
if (ch[3] == '+') {
result = fs1.add(fs2);
} else if (ch[3] == '-') {
result = fs1.sub(fs2);
}
if (result.fz % result.fm == 0) {
System.out.println(result.fz / result.fm);
} else {
System.out.println(result.fz + "/" + result.fm);
}
}
sc.close();
}
}
又是遇到错部分样例的情况,因为当有分子负数时,gcd也时一个负数,分子分母都除以gcd那么分子变正,分母变负,所以我们要特判一下后做个转换。
AC代码:
class Fs {
int fz, fm;
Fs(int a, int b){
this.fz = a;
this.fm = b;
simplify();
}
public int gcd(int a, int b) {
return (b==0)?a:gcd(b, a%b);
}
public void simplify() {
int gcd = gcd(this.fz, this.fm);
fz /= gcd;
fm /= gcd;
if (fm < 0) {
fz = -fz;
fm = -fm;
}
}
public Fs add(Fs c) {
int newfz = this.fz*c.fm+c.fz*this.fm;
int newfm = this.fm*c.fm;
return new Fs(newfz, newfm);
}
public Fs sub(Fs c) {
int newfz = this.fz*c.fm - c.fz*this.fm;
int newfm = this.fm * c.fm;
return new Fs(newfz, newfm);
}
}
分数计算
(函数题)该题目实现了分数的表示,分数的加法和乘法。该题目的输入不需要考虑输入分母为“0”。注意,例如当输入是分子是4,分母是8的时候,分数应该是1/2,而不是4/8.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
Fraction a = new Fraction(in.nextInt(), in.nextInt());
Fraction b = new Fraction(in.nextInt(),in.nextInt());
a.print();
b.print();
a.plus(b).print();
a.multiply(b).print();
in.close();
}
}
/* 请在这里填写答案 */
自己做的时候一直错一个样例,搜了一下发现当分子分母一样时应该输出1,改了之后就对行了。
AC代码:
class Fraction{
int fz, fm;
Fraction(int a, int b){
this.fz = a;
this.fm = b;
}
public static int gcd(int a, int b) {
return (b==0)?a:gcd(b, a%b);
}
public void print() {
if (this.fz == this.fm) {
System.out.print("1"+" ");
return ;
}
int gg = gcd(this.fz, this.fm);
System.out.print(this.fz/gg+"/"+this.fm/gg+" ");
}
public Fraction plus(Fraction c) {
int lcm = this.fm*c.fm/gcd(this.fm, c.fm);
int p1 = lcm/this.fm;
int p2 = lcm/c.fm;
Fraction pp = new Fraction(this.fz*p1+c.fz*p2, lcm);
return pp;
}
public Fraction multiply(Fraction c) {
Fraction pp = new Fraction(this.fz*c.fz, this.fm*c.fm);
return pp;
}
}
求圆锥体积(泛型)
请用泛型完成该题目,输入为底面圆的半径和圆锥的高(两个整型),输出为该圆锥的体积(保留小数点后两位)。注:在涉及园的计算中请用Math.PI。
在这里给出函数被调用进行测试的例子。例如:
import java.util.Scanner;
public class Main {
public static void main(String args[]) {
int i,j;
Scanner sc=new Scanner(System.in);
i=sc.nextInt();
j=sc.nextInt();
sc.close();
Circle circle=new Circle(i);
Cone<Circle> coneOne=new Cone<Circle>(circle);//创建一个(圆)锥对象
coneOne.setHeight(j);
System.out.printf("%.2f\n",coneOne.computerVolume());
}
}
/* 请在这里填写答案 */
AC代码:
class Circle{
int r;
Circle(int r){
this.r = r;
}
}
class Cone<T>{
T circle;
int h;
Cone(Circle circle){
this.circle = (T)circle;
}
public void setHeight(int h) {
this.h = h;
}
public double computerVolume() {
return (Math.PI*((Circle)circle).r*((Circle)circle).r*this.h)/3;
}
}
BMI异常处理
BMI(Body Mass Index,身体质量指数)的计算公式为:BMI = 体重(千克)÷ 身高(米)的平方。
BMI说明
BMI<18.5 Underweight
18.5<=BMI<=24.0 Normal
25.0<=BMI<=30.0 Overweight
30.0<BMI Obese
本题要求实现两个类,一个为Bmi,可以设置和读取BMI数值。一个为BmiException,当BMI不在正常范围内,就抛出异常,其信息有3个(Underweight、Overweight、Obese)。整个程序的输入值为两个:体重(千克),身高(米);均为double类型。通过计算输入值,如果BMI值在正常范围内,就返回BMI的整数值;如果不在正常范围以内,则通过计算,返回(Underweight、Overweight、Obese)其中一个。
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
double weight = input.nextDouble();
double height = input.nextDouble();
Bmi test = new Bmi();
try{ test.setBmi(weight, height);
System.out.println(test.getBmi());
}
catch(BmiException e) {
System.out.println(e.toString());
}
}
}
/* 请在这里填写答案 */
AC代码:
class Bmi{
double value;
public void setBmi(double w, double h) throws BmiException {
double bmi = w/(h*h);
this.value = bmi;
if (bmi < 18.5) {
throw new BmiException("Underweight");
}
else if (bmi >= 24.0 && bmi <= 30.0) {
throw new BmiException("Overweight");
}
else if (bmi > 30.0) {
throw new BmiException("Obese");
}
}
public double getBmi() {
return value;
}
}
class BmiException extends Exception{
String message;
public BmiException(String message) {
this.message = message;
}
public String toString() {
return message;
}
}
分解质因数
将一个正整数分解质因数。不用考虑输入为0,1或者负数。
输入格式:
100
输出样例:
100=2*2*5*5
AC代码:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int a[] = new int[100];
int num = 0, nn = n;
int m = 2;
while (nn != m) {
for (m = 2; m<=nn; m++) {
if (nn % m == 0) {
a[num++] = m;
break;
}
}
nn /= m;
}
a[num] = m;
// System.out.print(num);
System.out.print(n+"=");
for (int i = 0; i<=num; i++) {
if (i == 0) {
System.out.print(a[i]);
}
else System.out.print("*"+a[i]);
}
}
}
打印大小写字母
仔细阅读接口和主程序的调用,完成程序,使得程序可以正常打印26个大小写字母。
输入样例:
28
5
输出样例:
AB
abcde
import java.util.Scanner;
public class Main {
public static void main(String[] args){
int N,n;
Scanner input=new Scanner(System.in);
N=input.nextInt();
n=input.nextInt();
input.close();
InterfaceA a =new Print();
a.setN(N);
a.printCapitalLetter();
InterfaceB b=new Print();
b.printLowercaseLetter(n);
}
}
interface InterfaceA {
void setN(int n);
void printCapitalLetter();
}
interface InterfaceB {
void printLowercaseLetter(int n);
}
/* 请在这里填写答案 */
AC代码:
class Print implements InterfaceA, InterfaceB{
int n;
public void setN(int n) {
if (n == 0) this.n = 0;
else if (n%26==0) this.n = n;
else this.n = n%26;
}
public void printCapitalLetter() {
for (int i = 0; i<n; i++) {
System.out.print((char)('A'+i));
}
System.out.println();
}
public void printLowercaseLetter(int n) {
if (n == 0) this.n = 0;
else if (n%26==0) this.n = n;
else this.n = n%26;
for (int i = 0; i<this.n; i++) {
System.out.print((char)('a'+i));
}
System.out.println();
}
}
请完成父类
裁判测试程序样例中展示的是一段定义基类People、派生类Student以及测试两个类的相关Java代码,其中缺失了部分代码,请补充完整,以保证测试程序正常运行。
程序样例
class People{
protected String id;
protected String name;
/** 你提交的代码将被嵌在这里(替换此行) **/
}
class Student extends People{
protected String sid;
protected int score;
public Student() {
name = "CUIT Student";
}
public Student(String id, String name, String sid, int score) {
super(id, name);
this.sid = sid;
this.score = score;
}
public void say() {
System.out.println("I'm a student. My name is " + this.name + ".");
}
}
public class Main {
public static void main(String[] args) {
Student zs = new Student();
zs.setId("4700X");
zs.setName("Zhang San");
zs.say();
System.out.println(zs.getId() + " , " + zs.getName());
Student ls = new Student("330106","Li Si","2018000007",98);
ls.say();
System.out.println(ls.getId() + " : " + ls.getName());
People ww = new Student();
ww.setName("Wang Wu");
ww.say();
People zl = new People("370202", "Zhao Liu");
zl.say();
}
}
输出样例:
I'm a student. My name is Zhang San.
4700X , Zhang San
I'm a student. My name is Li Si.
330106 : Li Si
I'm a student. My name is Wang Wu.
I'm a person. My name is Zhao Liu.
AC代码:
People(){}
People(String id, String name){
this.id = id;
this.name = name;
}
public void setId(String id) {
this.id = id;
}
public void setName(String name) {
this.name = name;
}
public String getId() {
return id;
}
public String getName() {
return name;
}
public void say() {
System.out.println("I'm a person. My name is "+this.name+".");
}
完成学生及教师的设计(包括集合)
已知Main类、Person类的设计,完成Student类,Teacher类、MyTool类的设计。
Student类继承了Person,拥有私有属性int类型的sno和String类型的major,分别代表学号与所学专业;提供对应的set,get方法;比较方法完成按照学号比较。
Teacher类继承了Person,拥有私有属性int类型的tno和String类型的subject,分别代表教师编号与所授科目;提供对应的set,get方法;比较方法完成按年龄比较。
MyTool类中提供方法public static void separateStu_T(List persons,List teachers,List students){},方法 separateStu_T的功能是将persons线性表中的 teacher,student分别放到teachers,students两个线性表中。
测试程序样例:
import java.util.*;
public class Main {
public static void main(String[] args) {
List persons=getPersons(); //得到一个所有人的线性表
List teachers=new ArrayList();
List students=new ArrayList();
MyTool.separateStu_T( persons,teachers,students); //将persons线性表中的 teacher,student分别放到teachers,students两个线性表中
Collections.sort(teachers); //对教师线性表排序
Collections.sort(students); //对学生线性表排序
showResult(teachers); //显示教师线性表排序以后的结果
showResult(students); //显示学生线性表排序以后的结果
}
public static List getPersons()
{
List persons=new ArrayList();
Scanner in=new Scanner(System.in);
Person person=null;
int num=Integer.parseInt(in.nextLine());
for(int i=0;i<num;i++)
{ String str=in.nextLine();
String []data=str.split(",");
if(data[0].equalsIgnoreCase("student"))
person=new Student(Integer.parseInt(data[1]),data[2],data[3],Integer.parseInt(data[4]),data[5]);
else if (data[0].equalsIgnoreCase("teacher"))
person=new Teacher(Integer.parseInt(data[1]),data[2],data[3],Integer.parseInt(data[4]),data[5]);
else person=null;
persons.add(person);
}
return persons;
}
public static void showResult(List persons)
{
for(int i=0;i<persons.size();i++)
{
Person per=(Person)persons.get(i);
System.out.println(per.getName()+","+per.getGender()+","+per.getAge());
}
}
}
abstract class Person implements Comparable
{ private String name;
private String gender;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public Person(String name, String gender, int age) {
super();
this.name = name;
this.gender = gender;
this.age = age;
}
}
/* 请在这里填写答案 */
输入样例:
5
student,1001,Tom1,female,18,computer
teacher,2001,Jake1,female,35,datastructer
student,1002,Tom2,male,19,computer
student,1003,Tom3,female,20,software
teacher,2002,Jake2,female,33,database
输出样例:
Jake2,female,33
Jake1,female,35
Tom3,female,20
Tom2,male,19
Tom1,female,18
AC代码:
class Student extends Person{
int sno;
String major;
public Student(int sno, String name, String gender, int age, String major) {
super(name, gender, age);
// TODO Auto-generated constructor stub
this.sno = sno;
this.major = major;
}
public int compareTo(Object arg0) {
return -(this.sno-((Student)arg0).sno);
}
}
class Teacher extends Person{
int ton;
String subject;
public Teacher(int ton, String name, String gender, int age, String subject) {
super(name, gender, age);
// TODO Auto-generated constructor stub
this.ton = ton;
this.subject = subject;
}
public int compareTo(Object arg0) {
return this.getAge()-((Teacher)arg0).getAge();
}
}
class MyTool{
public static void separateStu_T(List persons,List teachers,List students){
Iterator It = persons.iterator();
while (It.hasNext()) {
Person p = (Person)It.next();
if (p instanceof Teacher) {
teachers.add((Teacher)p);
}
else {
students.add((Student)p);
}
}
}
}
数字字符串对齐处理
分别输入两个纯数字的字符串,把较短的一个字符串前面填上“0”,使得两个字符串一样长,然后分别输出。
测试程序样例:
在这里给出函数被调用进行测试的例子。例如:
import java.util.Scanner;
public class Main {
public static void main(String[] args){
String tempa, tempb;
Scanner input = new Scanner(System.in);
tempa = input.nextLine();
tempb = input.nextLine();
int c = Math.max(tempa.length(), tempb.length());
int[] a = new int[c] ;
int[] b = new int[c];
Transform(tempa, tempb, a, b);
for(int i=0;i<c;i++) {
System.out.printf("%d",a[i]);
}
System.out.println();
for(int i=0;i<c;i++) {
System.out.printf("%d",b[i]);
}
}
/* 请在这里填写答案 */
}
输入样例:
12345
89
输出样例:
12345
00089
AC代码:
public static void Transform(String a, String b, int[] A, int[] B) {
int n = Math.abs(a.length() - b.length());
if (a.length() > b.length()){
for (int i=0; i<n; i++){
B[i] = 0;
}
for (int i = 0; i<b.length(); i++){
B[i+n] = b.charAt(i) - '0';
}
for (int i = 0; i<a.length(); i++){
A[i] = a.charAt(i) - '0';
}
}
else{
for (int i=0; i<n; i++){
A[i] = 0;
}
for (int i = 0; i<a.length(); i++){
A[i+n] = a.charAt(i) - '0';
}
for (int i = 0; i<b.length(); i++){
B[i] = b.charAt(i) - '0';
}
}
}
求月份中的天数(日历)
本题要求实现一个方法,可返回任一月份中具体有多少天。
注:2月天数和该年是否为闰年相关
测试程序样例:
在这里给出函数被调用进行测试的例子。例如:
import java.util.Scanner;
public class Main {
public static void main(String[] args){
Scanner input = new Scanner(System.in);
int year = input.nextInt();
int month = input.nextInt();
System.out.println(getNumberOfDaysInMonth(year, month));
}
/* 请在这里填写答案 */
}
输入样例:
2020
9
输出样例:
30
AC代码:
public static int getNumberOfDaysInMonth(int year, int month){
int flag = 0;
int res = 0;
if ((year % 4 == 0 && year % 100!= 0) || year % 400 == 0){
flag = 1;
}
if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12){
res = 31;
}
else if (month == 4 || month == 6 || month == 9 || month == 11){
res = 30;
}
else if (month == 2){
res = 28 + flag;
}
return res;
}
打印一个月的日历(日历)
本题要求实现一个方法,用户输入年代和月份,方法输出当月日历。
注:相关打印设置为:System.out.print(" "); //打印1号前的空档,空1天打印1次;
System.out.printf("%4d",i); //打印具体日期;
一个月打印完了以后换行。
测试程序样例:
在这里给出函数被调用进行测试的例子。例如:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int year=input.nextInt();
int month = input.nextInt();
printMonth(year, month);
input.close();
}
public static void printMonth(int year, int month){
printMonthTitle(year, month);
printMonthBody(year, month);
}
public static void printMonthTitle(int year, int month){
System.out.println(" "+getMonthName(month)+ " " + year);
System.out.println("-----------------------------");
System.out.println(" Sun Mon Tue Wed Thu Fri Sat");
}
/* 请在这里填写答案 */
}
输入样例:
2020
9
输出样例:
September 2020
-----------------------------
Sun Mon Tue Wed Thu Fri Sat
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30
AC代码:
public static String getMonthName(int month){
String []months ={"January","February","March","April","May","June","July","August","September","October","November","December"};
return months[month-1];
}
public static void printMonthBody(int year, int month){
int []days= {31,28,31,30,31,30,31,31,30,31,30,31};
int sum = 0;
for (int i = 1800; i<year; i++){
for (int j = 0; j<12; j++){
if (j == 1 && isLeapYear(i)){
sum += 29;
continue;
}
sum += days[j];
}
}
if (isLeapYear(year)){
days[1] = 29;
}
for (int i = 0; i<month-1; i++){
if (i==1 && isLeapYear(year)){
sum += 29;
continue;
}
sum += days[i];
}
int day[] = {3, 4, 5, 6, 7, 1, 2};
int index = day[sum%7];
for (int i = 0; i<index && index < 7; i++){
System.out.print(" ");
}
for (int i = 1; i<=days[month-1]; i++){
if ((i+index)%7 == 0 || i == days[month-1]){
System.out.printf("%4d\n", i);
}
else System.out.printf("%4d", i);
}
}
public static boolean isLeapYear(int y){
if ((y % 4 == 0 && y % 100 != 0) || y % 400 == 0) return true;
else return false;
}
日历类
按照要求构建一个MyDate类,完成闰年判断,计算当月天数和计算本月第一天是星期几的基本功能。注:1800年1月1日是周三。
测试程序样例:
在这里给出该类被调用进行测试的代码。
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int year = input.nextInt();
int month = input.nextInt();
MyDate a = new MyDate(year, month);
System.out.println(a.isLeapYear());
System.out.println(a.getMonthDay());
System.out.println(a.getStartDay());
}
}
/* 请在这里填写答案 */
输入样例:
2020 10
输出样例:
true
31
Thu
AC代码:
class MyDate {
int y, m;
int days[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
public MyDate(int year, int month) {
y = year;
m = month;
}
public String isLeapYear() {
if (y % 4 == 0 && y % 100!= 0 || y % 400 == 0) {
return "true";
}
else return "false";
}
public boolean isleap(int year){
if (year % 4 == 0 && year % 100!= 0 || year % 400 == 0) {
return true;
}
else return false;
}
public int getMonthDay() {
if (m == 2 && isleap(y)){
return 29;
}
return days[m-1];
}
public String getStartDay() {
String []week = {"Wed", "Thu", "Fri", "Sat","Sun", "Mon", "Tue"};
int sum = 0;
for (int i = 1800; i<y; i++){
for (int j = 0; j<12; j++){
if (j == 1 && isleap(i)){
sum += 29;
}
else sum += days[j];
}
}
for (int i = 0; i<m-1; i++){
if (i == 1 && isleap(y)){
sum += 29;
}
else sum += days[i];
}
int index = sum % 7;
return week[index];
}
}
计算当月1号是星期几(日历)
本题要求实现一个方法,可计算出每个月1号对应的星期数。例如用户输入2020,9,2020年9月1日对应的是星期二,则该应该返回2。
注:1800年1月1日是周三。
计算的范围是1800年及以后。
测试程序样例:
在这里给出方法被调用进行测试的例子。例如:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int year = input.nextInt();
int month = input.nextInt();
System.out.println(getStartDay(year, month));
}
/* 请在这里填写答案 */
}
输入样例:
2020
9
输出样例:
2
AC代码:
public static int getStartDay(int year, int month){
int days[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
int sum = 0;
for (int i = 1800; i<year; i++){
for (int j = 0; j<12; j++){
if (j == 1 && isLeapYear(i)){
sum += 29;
}
else sum += days[j];
}
}
for (int i = 0; i<month-1; i++){
if (i == 1 && isLeapYear(year)){
sum += 29;
}
else sum += days[i];
}
int week[] = {3, 4, 5, 6, 7, 1, 2};
int index = sum % 7;
return week[index];
}
public static boolean isLeapYear(int year){
if ((year % 4 == 0 && year % 100!= 0) || year % 400 == 0){
return true;
}
else return false;
}
根据已有类Worker,使用LinkedList编写一个WorkerList类,实现计算所有工人总工资的功能。
Main类:在main方法中,调用constructWorkerList方法构建一个Worker对象链表,调用computeTotalSalary方法计算总工资并输出到屏幕。
根据要求,编写WorkerList类的构造方法和方法。编程要求如下:
数据使用Scanner对象从键盘读入;
constructWorkerList方法:从键盘读入工人数量workerNum,调用readInWorker方法读入workerNum个工人,将每个工人对象添加到链表中,最后返回链表。
readInWorker方法:使用scanner从键盘读入一个工人的姓名、年龄和工资,构建一个Worker对象并返回
computeTotalSalary方法:计算链表中所有工人的工资总和并返回。
提示: Scanner对象读入字符串的方法:
next()方法读入一个字符串,读到空白符结束;(本题中使用next()方法读入字符串)
nextLine()也是读入一个字符串,但读取到回车(也就是"\r")结束。
AC代码:
class WorkerList{
Worker readInWorker() {
Scanner sc=new Scanner(System.in);
Worker a= new Worker();
String nam=sc.next();
double sal=sc.nextDouble();
a.setSalary(sal);
a.setName(nam);
sc.close();
return a;
}
List<Worker> constructWorkerList()
{
Scanner sc=new Scanner(System.in);
List<Worker> list=new ArrayList<Worker>();
int n=sc.nextInt();
//Worker w=new Worker();
String nc;
double sa;
for(int i=0;i<n;i++)
{
Worker w=new Worker();
// w=readInWorker();
nc=sc.next();
sa=sc.nextDouble();
w.setName(nc);
w.setSalary(sa);
list.add(w);
}
sc.close();
return list;
}
double computeTotalSalary(List<Worker> list)
{
double sum=0;
for (Worker w : list){
sum += w.getSalary();
}
return sum;
}
}
编写Student类,使用泛型和集合框架编写StudentList类,实现计算班级平均分的功能。
Main类:在main方法中,调用constructStudentList方法构建一个Worker对象链表,调用computeAverageScore方法计算一个班级的平均分并输出到屏幕。 根据要求,编写Student类和StudentList类。
Student类的编程要求如下:
- 成员变量包括:学生姓名(String name)、班级编码(String classCode)、分数(int score)
- 根据程序需求编写构造方法。
- 根据程序需求编写set和get方法。
StudentList类的编程要求如下:
- 根据程序需求编写构造方法。
- constructStudentList方法:调用readInStudent方法读入多个学生信息,将Student对象添加到链表中,构建一个Student对象链表,最后返回链表。
- readInStudent方法:使用scanner从键盘读入一个学生的姓名、班级和分数,构建一个Student对象并返回。
- computeAverageScore(List list)方法:遍历链表,累加链表中所有学生人数和总分数,计算出某个班级平均分并返回。
测试程序样例:
import java.util.*;
public class Main {
public static void main(String[] args) {
StudentList sl=new StudentList();
List<Student> list=sl.constructStudentList();
System.out.println(sl.computeAverageScore(list));
}
}
/* 请在这里填写答案 */
/*请在这里补充Student类*/
/*请在这里补充StudentList类*/
输入样例:
class191
Tom class191 100
Jerry class192 95
Owen class193 90
Jim class191 80 #
输出样例:
90.0
AC代码:
/*请在这里补充Student类*/
class Student {
String name, ccode;
double score;
public Student() {}
public Student(String name, String ccode, double score) {
this.name = name;
this.ccode = ccode;
this.score = score;
}
public void setName(String name) {
this.name = name;
}
public void setCcode(String c){
this.ccode = c;
}
public void setScore(double s){
this.score = s;
}
public String getName(){
return name;
}
public String getCcode(){
return ccode;
}
public double getScore(){
return score;
}
}
/*请在这里补充StudentList类*/
class StudentList {
List<Student> constructStudentList(){
List<Student> list = new ArrayList<Student>();
Scanner sc = new Scanner(System.in);
String className = sc.next();
String name = sc.next();
while (!name.equals("#")){
String cn = sc.next();
double score = sc.nextDouble();
Student s = new Student(name, cn, score);
if (cn.equals(className)){
list.add(s);
}
name = sc.next();
}
return list;
}
Student readInStudent(){
Scanner sc = new Scanner(System.in);
String name = sc.next();
String ccode = sc.next();
double score = sc.nextDouble();
Student s = new Student(name, ccode, score);
return s;
}
double computeAverageScore(List<Student> list){
double sum = 0;
for (Student s : list){
sum += s.getScore();
}
return sum / list.size();
}
}
完成链表的增加元素功能
根据题目要求,实现链性表元素的添加功能。
Append(T item)
初始条件:链性表未满。
操作结果:将值为item的新元素添加到表的末尾。
你需要完成构造函数及Append方法。
测试程序样例:
在这里给出函数被调用进行测试的例子。例如:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int x = input.nextInt();
LinkList<Integer> a = new LinkList<Integer>();
for(int i =0; i < x; i++) {
a.Append(i);
}
System.out.println(a);
}
}
interface IListDS<T> {
void Append(T item);
}
class Node<T> {
T data;
Node<T> next;
public Node() {
next = null;
}
public Node(T val) {
data = val;
next = null;
}
public Node(Node<T> p) {
next = p;
}
public Node(T val,Node<T> p) {
data = val;
next = p;
}
}
class LinkList<T> implements IListDS<T> {
public Node<T> head;
/* 请在这里填写答案 */
public String toString() {
String str = "(";
Node<T> p = head.next;
if(p != null) {
str = str + p.data;
p = p.next;
}
while(p != null) {
str = str + ","+p.data;
p = p.next;
}
str = str + ")";
return str;
}
}
输入样例:
15
输出样例:
(0,1,2,3,4,5,6,7,8,9,10,11,12,13,14)
AC代码:
public void Append(T item){
Node<T> newNode = new Node<T>(item);
if(head == null) {
head = new Node<T>();
head.next = newNode;
} else {
Node<T> p = head.next;
while(p.next != null) {
p = p.next;
}
p.next = newNode;
}
}
思路:犹如c语言的链表创建。
完成顺序表的增加元素功能
根据题目要求,实现线性表元素的添加功能。
Append(T item)
初始条件:线性表未满。
操作结果:将值为item的新元素添加到表的末尾。
你需要完成构造函数及Append方法。
测试程序样例:
在这里给出函数被调用进行测试的例子。例如:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int n = input.nextInt();
SeqList<Integer> a = new SeqList<Integer>(n);
for(int i =0; i < n; i++) {
a.Append(i);
}
System.out.println(a);
}
}
interface IListDS<T> {
void Append(T item);
}
class SeqList<T> implements IListDS<T> {
public T[] data;
public int maxsize;
public int last;
/* 请在这里填写答案 */
public String toString() {
String str = "(";
str = str + data[0];
for(int i = 1; i <= last; ++i)
str = str + "," + data[i];
str = str + ")";
return str;
}
}
输入样例:
10
输出样例:
(0,1,2,3,4,5,6,7,8,9)
AC代码:
public SeqList(int size) {
data = (T[]) new Object[size];
maxsize = size;
last = -1;
}
public void Append(T item){
data[++last] = item;
}
思路:主要在于顺序表的初始化。
多线程累加
启动10个线程,第一个线程从1加到10,第二个线程从11加到20.....第十个线程从91加到100,最后再把10个线程结果相加。线程类的已经完成,请完成Main类,实现输出。
输出样例:
The 1 time: 55
The 2 time: 155
The 3 time: 255
The 4 time: 355
The 5 time: 455
The 6 time: 555
The 7 time: 655
The 8 time: 755
The 9 time: 855
The 10 time: 955
Total is 5050
代码:
class Thread_test extends Thread
{
int number;
public static int sum;
public Thread_test(int n) //构造函数
{
number=n;
}
public static synchronized void add(int num){ //同步方法
sum += num;
}
public void run()
{
int count=0;
for(int i=0;i<10;i++)
{
count+=number+i;
}
System.out.println("The "+((int)number/10+1)+" time: "+count);
add(count);
}
}
/* 请在这里填写答案 */
public class Main{
public static void main(String args[]) {
Thread_test[] th = new Thread_test[10];
for (int i = 0; i<10; i++){
th[i] = new Thread_test(i*10+1);
th[i].start();
try {
th[i].join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("Total is "+Thread_test.sum);
}
}
知识点:
-
join()
方法:join()
是Thread
类的方法。调用它会使当前线程(即执行main
方法的线程)进入等待状态,直到test[i]
线程执行完毕。- 也就是说,
main
线程在执行到这行代码时,会等待test[i]
线程完成其执行(即运行run()
方法)后,才会继续执行下一行代码。