编程题部分 - Java

2022年01月14日 阅读数:3
这篇文章主要向大家介绍编程题部分 - Java,主要内容包括基础应用、实用技巧、原理机制等方面,希望对大家有所帮助。

Circle类:

输入:

4
5
-4
-2

输出:

this is a constructor
Circle [radius=2]
c1:area=12
this is a constructor
Circle [radius=2]
Circle [radius=4]
c2:area=50
this is a constructor with para
Circle [radius=5]
c3:area=78
this is a constructor
Circle [radius=2]
c1:area=12
this is a constructor
Circle [radius=2]
Circle [radius=2]
c2:area=12
this is a constructor with para
Circle [radius=2]
c3:area=12

代码:

import java.util.Scanner;
import java.lang.Math.*;

public class Main {
    public static class Circle {
        private int radius;
        Circle() {
            this.radius = 2;
            System.out.println("this is a constructor");
        }
        Circle(int radius) {
            this.radius = radius;
            if (this.radius <= 0) {
                this.radius = 2;
//                System.out.println("this is a constructor with para");
            }
            System.out.println("this is a constructor with para");

        }
        public void setter(int r){
            this.radius = r;
            if(r <= 0){
                this.radius = 2;
            }
        }
        public int getter(){
            return this.radius;
        }
        public int gerArea(){
            double s;
            s = Math.PI * radius * radius;
            return (int)s;
        }
        public String toString(){
            String str = "Circle [radius=" + this.radius + "]";
            return str;
        }
    }
    public static void main(String[]args){
//        c1:
        Circle c1 = new Circle();
        String str1 = c1.toString();
        System.out.println(str1);
        int s1 = c1.gerArea();
        System.out.println("c1:area=" + s1);
//        c2:
        Circle c2 = new Circle();
        String str2 = c2.toString();
        System.out.println(str2);
        Scanner in = new Scanner(System.in);
        int r = in.nextInt();
        c2.setter(r);
        String str22 = c2.toString();
        System.out.println(str22);
        int s2 = c2.gerArea();
        System.out.println("c2:area=" + s2);
//        c3:
        int rr = in.nextInt();
        Circle c3 = new Circle(rr);
        String str3 = c3.toString();
        System.out.println(str3);
        int s3 = c3.gerArea();
        System.out.println("c3:area=" + s3);
    }
}
View Code

 

设计一个风扇Fan类:

设计一个名为Fan的类表示一个风扇。这个类包括:

1.三个名为SlOW、MEDIUM和FAST,其值为一、2和3常量表示风扇的速度。

2.一个名为speed的int类型私有数据域表示风扇的速度(默认值为SLOW)。

3.一个名为on的boolean类型私有数据域表示风扇是否打开(默认值为false)。

4.一个名为radius的double类型私有数据域表示风扇的半径(默认值为5)。

5.一个名为color的string类型数据域表示风扇的颜色(默认值为white)。

6.这四个成员变量(数据域)的访问器和修改器。

7.一个无参构造方法;

8.一个有参构造方法 public Fan(int fanSpeed,boolean fanOn,double fanRadius,String fanColor) { ... },

9.一个名为toString()的方法返回描述风扇的字符串。若是风扇是打开的,那么该方法在一个组合的字符串中返回风扇的速度、颜色和半径。若是风扇没有打开,该方法就会返回一个由"fan is off"和风扇颜色以及半径组合成的字符串。

请在本身的草稿本上画出UML图,养成良好的设计习惯。

要求:建立两个Fan对象:

第一个对象利用无参构造方法构造默认风扇对象Fan1;

第二个对象依据输入的风扇属性,调用有参构造方法构造自定义风扇对象Fan2。

经过调用它们的toString方法显示这些对象。

输入:

2
True
6
Red 

输出:

-------
Default
-------
speed 1
color white
radius 5.0
fan is off
-------
My Fan
-------
speed 2
color Red
radius 6.0
fan is on

代码:

import java.util.*;
class Fan
{
    static int SLOW=1;
    static int MEDIUM=2;
    static int FAST=3;
    private int speed = 1;
    private boolean on = false;
    private double radius = 5;
    public String color = "white";

    public Fan ()
    {}
    public Fan(int fanSpeed,boolean fanOn,double fanRadius,String fanColor) {
      speed = fanSpeed;
      on = fanOn;
      radius =  fanRadius;
      color = fanColor;
    }
    public String toString()
    {
        if(!on) {
            return "speed "+speed+"\ncolor "+color+"\nradius "+radius+"\nfan is off";
        }
        return "speed "+speed+"\ncolor "+color+"\nradius "+radius+"\nfan is on";
    }
    public void setSpeed(int s)
    {
        speed = s;
    }
    public void setcolor(String co)
    {
        color = co;
    }
    public void seton(boolean oon)
    {
      on = oon;
    }
    public int getspeed()
    {
        return speed;
    }
    public String getcolor()
    {
        return color;
    }
    public boolean geton()
    { 
        return on;
    }
    public double getradius()
    {
        return radius;
    }
    public void setradius(double r)
    {
        radius = r;
    }
}


public class Main {
    public static void main(String[] args)
    {
      Scanner in =new Scanner(System.in);
      int a = in.nextInt();
      boolean b = in.nextBoolean();
      double c = in.nextDouble();
      String d = in.next();
      Fan f1 = new Fan();
      Fan f2 = new Fan();
      f2.setcolor(d);
      f2.setSpeed(a);
      f2.setradius(c);
      f2.seton(b);
      System.out.println("-------");
      System.out.println("Default");
      System.out.println("-------");
      System.out.println(f1.toString());
      System.out.println("-------");
      System.out.println("My Fan");
      System.out.println("-------");
      System.out.println(f2.toString());

    }
}
View Code

 

设计一个BankAccount类:

 输入:

700
70
7

输出:

700
630
637

代码:

import java.util.Scanner;

public class Main {
    public static void main(String[]args){

        Scanner in = new Scanner(System.in);
        int a1 = in.nextInt();
        int a2 = in.nextInt();
        int a3 = in.nextInt();
        BankAccount b = new BankAccount(a1);
        int a = b.getBlance();
        System.out.println(a);
        b.withdraw(a2);
        b.deposit(a3);
    }
    public static class BankAccount{
        public int balance;
        BankAccount(){
            this.balance = 0;
        }
        BankAccount(int balance){
            this.balance = balance;
        }
        public int getBlance(){
            return this.balance;
        }
        public void withdraw(int amount){
            this.balance = this.balance - amount;
            System.out.println(this.balance);
        }
        public void deposit(int a){
            this.balance += a;
            System.out.println(this.balance);
        }

    }
}
View Code

 

学生类设计:

 输入:

tom 6
jerry 8

输出:

无参构造方法
name:无名,age:7
name:tom,age:7
无参构造方法
name:无名,age:7
name:jerry,age:8

代码:

import java.util.Scanner;

public class Main {
    public static void main(String[]args){
        Student s1 = new Student();
        Scanner in = new Scanner(System.in);
        String name = in.next();
        int age = in.nextInt();
        s1.setname(name);
        s1.setage(age);
        s1.display();
    }
    public static class Student{
        private String name;
        private int age;
        public void setname(String name){
            this.name = name;
        }
        public void setage(int age){
            this.age = age;
            if(age <= 6)
                this.age = 7;
        }
        public String getname(){
            return this.name;
        }
        public int getage(){
            return this.age;
        }
        Student(){
            System.out.println("无参构造方法");
            this.name = "无名";
            this.age = 7;
            System.out.println("name:无名,age:7");
        }
        Student(String name, int age){
            this.name = name;
            this.age = age;
        }
        public void display(){
            System.out.println("name:" + this.name + ",age:" + this.age);
        }
    }
}
View Code

 

定义类与建立对象:

输入:

输出:

this person is lili,her age is 19
this person is lucy,her age is 20

代码:

public class Main {
    public static void main(String[]args){
        Person p1 = new Person("lili", 19);
        Person p2 = new Person("lucy", 20);

    }
    public static class Person{
        public String name;
        public int age;
        Person(String name, int age){
            this.name = name;
            this.age = age;
            System.out.println("this person is " + this.name + ",her age is " + this.age);
        }
    }
}
View Code

 

继承覆盖综合练习-Person、Student、Employee、Company:

 

 

输入:

s zhang 23 false 001 net15
e wang 18 true 3000.51 IBM
s zhang 23 false 001 net15
e bo 25 true 5000.51 IBM
e bo 25 true 5000.52 IBM
e bo 18 true 5000.54 IBM
e tan 25 true 5000.56 IBM
e tan 25 true 5000.51 IBM
s wang 17 false 002 null
s wang 17 false 002 null
e hua 16 false 1000 null
s wang 17 false 002 net16
e hua 16 false 1000 null
e hua 18 false 1234 MicroSoft
!
continue

输出:

Employee:bo-18-true-IBM-5000.54
Employee:bo-25-true-IBM-5000.51
Employee:bo-25-true-IBM-5000.52
Employee:hua-16-false-null-1000.0
Employee:hua-16-false-null-1000.0
Employee:hua-18-false-MicroSoft-1234.0
Employee:tan-25-true-IBM-5000.56
Employee:tan-25-true-IBM-5000.51
Student:wang-17-false-002-null
Student:wang-17-false-002-null
Student:wang-17-false-002-net16
Employee:wang-18-true-IBM-3000.51
Student:zhang-23-false-001-net15
Student:zhang-23-false-001-net15
stuList
Student:wang-17-false-002-null
Student:wang-17-false-002-net16
Student:zhang-23-false-001-net15
empList
Employee:bo-18-true-IBM-5000.54
Employee:bo-25-true-IBM-5000.51
Employee:hua-16-false-null-1000.0
Employee:hua-18-false-MicroSoft-1234.0
Employee:tan-25-true-IBM-5000.56
Employee:tan-25-true-IBM-5000.51
Employee:wang-18-true-IBM-3000.51

代码:

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.Scanner;
public class Main {
    public static void main(String[] args) {
        Scanner se = new Scanner(System.in);
        ArrayList <Person> 列表=new ArrayList <Person>();
        while (true) {
            String s或e =se.next();
            if(s或e.equals("s")) {
                列表.add(new Student(se.next(),se.nextInt(),se.nextBoolean(),se.next(),se.next()));
            }else if(s或e.equals("e")) {
                列表.add(new Employee(se.next(),se.nextInt(),se.nextBoolean(),se.nextDouble(),new Company(se.next())));
            }else {
                break;
            }
        }
        Collections.sort(列表, new 排序类());
        for(Person 一我的:列表) {
            if(一我的 instanceof Student) {
                System.out.println(((Student)一我的).toString());
            }else {
                System.out.println(((Employee)一我的).toString());
            }
        }
        String 输入exit或其余=se.next();
        if(输入exit或其余.equals("exit")) {
            return;
        }else {
            ArrayList <Student> stuList=new ArrayList <Student>();
            ArrayList <Employee> empList=new ArrayList <Employee>();
            for(Person w:列表) {
                if(w instanceof Student) {
                    if(!stuList.contains((Student)w)) {
                        stuList.add((Student)w);
                    }
                }
                if(w instanceof Employee) {
                    if(!empList.contains((Employee)w)) {
                        empList.add((Employee)w);
                    }
                }
            }
            System.out.println("stuList");
            for(Student a:stuList) {
                System.out.println(a.toString());
            }
            System.out.println("empList");
            for(Employee a:empList) {
                System.out.println(a.toString());
            }
        }
    }
}
abstract class Person{
    String name;int age; boolean gender;
    public Person(String name, int age, boolean gender) {
        super();
        if(name.equals("null")) {
            this.name = null;
        }else {
            this.name = name;
        }
        this.age = age;
        this.gender = gender;
    }

    @Override
    public String toString() {
        return name + "-" + age + "-" + gender;
    }
    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        Person other = (Person) obj;
        if (age != other.age)
            return false;
        if (gender != other.gender)
            return false;
        if (name == null) {
            if (other.name != null)
                return false;
        } else if (!name.equals(other.name))
            return false;
        return true;
    }
    
}
class Student extends Person{
    String stuNo,clazz;
    public Student(String name, int age, boolean gender, String stuNo, String clazz) {
        super(name, age, gender);
        if(stuNo.equals("null")) {
            this.stuNo = null;
        }else {
            this.stuNo = stuNo;
        }
        if(clazz.equals("null")) {
            this.clazz = null;
        }else {
            this.clazz = clazz;
        }
    }
    @Override
    public String toString() {
        return "Student:" + super.toString()+"-"+ stuNo + "-" + clazz;
    }
    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (!super.equals(obj))
            return false;
        if (getClass() != obj.getClass())
            return false;
        Student other = (Student) obj;
        if (clazz == null) {
            if (other.clazz != null)
                return false;
        } else if (!clazz.equals(other.clazz))
            return false;
        if (stuNo == null) {
            if (other.stuNo != null)
                return false;
        } else if (!stuNo.equals(other.stuNo))
            return false;
        return true;
    }
    
}
class Company{
    String name;

    public Company(String name) {
        if(!name.equals("null")) {
            this.name = name;
        }else {
            this.name = null;
        }
    }

    @Override
    public String toString() {
        return name;
    }
    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        Company other = (Company) obj;
        if (name == null) {
            if (other.name != null)
                return false;
        } else if (!name.equals(other.name))
            return false;
        return true;
    }
}
class Employee extends Person{
    Company company; 
    double salary;
    public Employee(String name, int age, boolean gender, double salary, Company company) {
        super(name, age, gender);
        this.company = company;
        this.salary = salary;
    }
    @Override
    public String toString() {
        return "Employee:" +super.toString()+"-"+ company + "-" + salary ;
    }
    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (!super.equals(obj))
            return false;
        if (getClass() != obj.getClass())
            return false;
        Employee other = (Employee) obj;
        String newpersalary = new DecimalFormat("#.#").format(other.salary);
        String newthissalary = new DecimalFormat("#.#").format(this.salary);
        if (company == null) {
            if (other.company != null)
                return false;
        } else if (!company.equals(other.company))
            return false;
        if (!newpersalary.equals(newthissalary))
            return false;
        return true;
    }
}
class 排序类 implements Comparator<Person>{
    @Override
    public int compare(Person o1, Person o2) {
        if(o1.name.compareTo(o2.name)>0) {
            return 1;
        }else if(o1.name.compareTo(o2.name)<0) {
            return -1;
        }else {
            if(o1.age>o2.age) {
                return 1;
            }else if(o1.age<o2.age) {
                return -1;
            }else {
                return 0;
            }
        }
    }
}
View Code

 

设计一个Shape及其子类Oval:

 

 输入:

8 6

输出:

The area of Oval(a:8.0,b:6.0) is 150.79644480000002
The perimeterof Oval(a:8.0,b:6.0) is 44.42882862370954

代码:

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        double a = in.nextDouble();
        double b = in.nextDouble();
        Oval oval = new Oval(a, b);
        System.out.println("The area of " + oval.toString() + " is " + oval.area());
        System.out.println("The perimeterof " + oval.toString() + " is " + oval.perimeter());
    }
}
abstract class Shape{
    final double PI = 3.1415926;
    abstract double area();
    abstract double perimeter();
}
class Oval extends Shape {
    private double a;
    private double b;
    Oval(double a, double b){
        this.a = a;
        this.b = b;
    }
    Oval(){
        this.a = 0;
        this.b = 0;
    }
    @Override
    public double area(){
        return PI*a*b;
    }
    @Override
    public double perimeter(){
        return 2*PI*Math.sqrt((a*a+b*b)/2);
    }
    @Override
    public String toString() {
        return "Oval(a:" + a + ",b:" + b + ")";
    }
}
View Code

 

定义商品类,封装成员变量,输出对象:

输入:

WJ002 记事本 5.5

输出:

WJ002,记事本,5.5

代码:

import java.util.Scanner;

public class Main {
        public static void main(String[] args) {
            Scanner sc = new Scanner(System.in);
            String number = sc.next();//控制输入
            String name = sc.next();
            double price = sc.nextDouble();
            stuff a = new stuff(number, name, price);
            System.out.println(a.getNumber()+","+a.getName()+","+a.getPrice());//调用方法
        }

}
class stuff{
    private String number;
    private String name;
    private double price;
    public String getNumber() {
        return number;
    }
    public void setNumber(String number) {
        this.number = number;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public double getPrice() {
        return price;
    }
    public void setPrice(double price) {
        this.price = price;
    }
    stuff(String number, String name,double price ) {//带参的构造方法
        this.name = name;
        this.number = number;
        this.price = price;
    }
}
View Code

 

单词替换:

输入:

Although I am without you, I will always be ou you
ou
with

输出:

Although I am without you, I will always be with you

代码:

import java.util.Scanner;

public class Main{
    public static void main(String[]args){
        Scanner sc = new Scanner(System.in);
        String str = sc.nextLine();
        String tar = sc.next();
        String rep = sc.next();
        String[]s = str.split(" ");
        for(int i=0; i<s.length; i++){
            if(s[i].equals(tar)){
                s[i] = rep;
            }
        }
        String s1 = "";
        for(int j=0; j<s.length; j++){
            s1 += s[j] + " ";
        }
        System.out.println(s1.trim());
    }
}
View Code

 

判断登陆信息--Java字符串比较:

输入:

SwpuIot 123456

输出:

Welcome

代码:

import java.util.Scanner;

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

        if(admin.equals("SwpuIot") && passwd.equals("123456")){
            System.out.println("Welcome");
        }
        else if(admin.equals("SwpuIot") && !(passwd.equals("123456"))){
            System.out.println("Mismatch");
        }
        else {
            System.out.println("NotExist");
        }
    }
}
View Code

 

图书价格汇总:

输入:

Java程序设计:34 ;Web程序设计: 56;JSP程序设计:20

输出:

Java程序设计:34 
Web程序设计: 56
JSP程序设计:20
总价格为110

代码:

import java.util.ArrayList;
import java.util.Scanner;

public class Main {
    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        int sum = 0;
        String str = sc.nextLine();
        String[] s = str.split(";");
        ArrayList<String> strList = new ArrayList<>();
        for(String ss : s) {
            strList.add(ss);
        }
        for(String ss : strList) {
            System.out.println(ss);
            sum += Integer.parseInt(ss.substring(ss.indexOf(":") + 1).trim());
        }
        System.out.println("总价格为" + sum);
    }
}
View Code

 

StringBuilder:

 输入:

10
5
8
1000
800
900

输出:

567
0330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533

代码:

import java.util.Scanner;
import java.lang.StringBuilder;

public class Main {
    public static void main(String[]args){
        Scanner sc = new Scanner(System.in);
        while(sc.hasNextInt()){
            int n = sc.nextInt();
            int begin = sc.nextInt();
            int end = sc.nextInt();
            StringBuilder stringBuilder = new StringBuilder("");
            String str="";
            for(int i=0; i<n; i++){
                stringBuilder.append(i);
            }
            System.out.println(stringBuilder.substring(begin, end));
        }

    }
}
View Code

 

经过键盘输入一行字符,分别统计出其中英文字母、空格、数字和其它字符的个数:

输入:

rwrwewre2345asdJSJQI%^&(&   *&sdf YY( 2342-k'

输出:

字母个数:22
数字个数:8
空格个数:5
其余字符个数:10

代码:

import java.util.Scanner;

public class Main {
    public static void main(String[]args){
        Scanner sc = new Scanner(System.in);
        String str = sc.nextLine();
        int LetterCount=0, NumCount=0, RepCount=0, OtherCount=0;
        char[] c = str.toCharArray();
        for(int i=0; i<str.length(); i++){
            if((c[i]>='A' && c[i]<='Z')||(c[i]>='a'&&c[i]<='z')){
                LetterCount ++;
            }
            else if(c[i]>=47 && c[i]<=57){
                NumCount ++;
            }
            else if(c[i]==32){
                RepCount ++;
            }
            else
                OtherCount++;
        }
        System.out.println("字母个数:"+LetterCount);
        System.out.println("数字个数:"+NumCount);
        System.out.println("空格个数:"+RepCount);
        System.out.println("其余字符个数:"+OtherCount);
    }
}
View Code

 

String的格式判断与内容提取:

输入1:

2020610120201702202051132020110320201706

输出1:

6101 1702 1706

 

 

 代码:

import java.util.Scanner;
public class Main {
    public static void main(String[] args) {
        Scanner scan=new Scanner(System.in);
        String s=scan.nextLine();
        if(s.length()%8!=0) {
            System.out.println("Wrong Format");
        }
        else if(s.indexOf(" ")!=-1) {
            System.out.println("Wrong Format");
        }
        else {
            String[] str=new String[s.length()/8];
            for(int i=1;i<s.length()/8+1;i++) {
                String a=s.substring((i-1)*8, i*8);
                if(a.substring(0,6).equals("202017")||a.substring(0,6).equals("202061")){
                    str[i-1]=a.substring(4,8);
                }
            }
            boolean flag=false;
            for(int j=0;j<str.length;j++) {
                if(str[j]!=null) {
                    if(j!=str.length-1) {
                        System.out.print(str[j]+" ");
                    }
                    else {
                        System.out.print(str[j]);
                    }
                }
            }
        }
    }
}
View Code

 

字符替换:

输入:

This is a pen.

输出:

Ghis is a pen.

代码:

import java.util.Scanner;

public class Main {
    public static void main(String[]args){
        Scanner sc = new Scanner(System.in);
        String str = sc.nextLine();
        char[] c = str.toCharArray();
        for(int i=0; i<str.length(); i++){
            if(c[i]>='A' && c[i]<='Z'){
                c[i] = (char)(155 - (int)c[i]);
            }
        }
        for(int i=0; i<c.length; i++){
            System.out.print(c[i]);
        }
    }
}
View Code

 

统计字符在字符串中第n次出现的位置:

 输入:

abcabcabc
2
a

输出:

4

代码:

import java.util.Scanner;
import java.lang.String;

public class Main {
    public static void main(String[]args){
        Scanner sc = new Scanner(System.in);
        String str = sc.nextLine();
        int n =sc.nextInt();
        String tar = sc.next();
        char c = tar.charAt(0);
        int flag = 0;
        for(int i=0; i<str.length(); i++){
            char ch = str.charAt(i);
            if(ch == c)
                n--;
            if(n == 0){
                flag = i + 1;
                break;
            }
        }
        if(n > 0)
            System.out.println("no");
        else if(n == 0)
            System.out.println(flag);
    }
}
View Code

 

倒置字符串并输出:

 输入:

I love China!

输出:

!anihC evol I
!

代码:

import java.util.Scanner;

public class Main {
    public static void main(String[]args){
        Scanner sc = new Scanner(System.in);
//        String str = sc.next();
//        StringBuilder sb = new StringBuilder(str);
//        System.out.println(sb.reverse().toString());
//        char[] c = str.toCharArray();
//        for(int i=0; i<c.length; i++){
//            System.out.print(c[i]);
//        }
//        System.out.println('\n');
//        System.out.println(c[c.length-1]);
        String line = sc.nextLine();
        char[] arr = line.toCharArray();
        String s ="";
        for (int i = arr.length-1; i >= 0; i--) {
            s = s + arr[i];    
        }
        System.out.println(s);
        System.out.println(arr[arr.length-1]);
    }
}
View Code

 

数组元素交换:

输入:

2 9 0 10

输出:

2
9
0
10
10
9
2
0

代码:

import java.util.*;
public class Main {
    static Scanner in = new Scanner(System.in);
    public static void main(String []args) {
        String line = in.nextLine();
        String str  = line;
        String []a = line.split(" ");
        int []x = new int[a.length];
        for(int i=0 ;i<a.length ; i++)
         x[i] = Integer.parseInt(a[i]);
        int min=x[0];
        int max = x[0];
    for(int i=1;i<x.length ; i++) {
        if(min>=x[i])
            min=x[i];
        if(max<=x[i])
            max = x[i];
    }
    for(int i=0 ;i<x.length;i++) {
        if(x[i]==max)
        {
            int temp = x[i];
            x[i] = x[0];
            x[0] = temp;
        }
        if(x[i]==min)
        {
            int temp = x[i];
            x[i] = x[x.length-1];
            x[x.length-1] = temp;
        }
    }
    for(int i=0 ;i<a.length;i++)
        System.out.println(a[i]);
    for(int i=0 ;i<x.length;i++)
        System.out.println(x[i]);
}}
View Code

 

构造函数与toString:

输入:

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.Scanner;

class Person{          //定义一个person类
    private String name = null;
    private int age = 0;
    private boolean gender = false;
    private int id = 0;
    
    public Person() {
        System.out.println("This is constructor");
        System.out.println(name+","+age+","+gender+","+id);
        System.out.println("Person [name="+name+", age="+age+", gender="+gender+", id="+id+"]");
    }
    
    public Person(String n, int a, boolean g) {      //编写有构造参数,赋值
        this.name = n;
        this.age = a;
        this.gender = g;
    }
    
    public String toString() {       //使用tostring方法
        System.out.println("Person [name="+this.name+", age="+this.age+", gender="+this.gender+", id="+0+"]");
        return name;
    }
}

public class Main {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        @SuppressWarnings("resource")
        Scanner reader = new Scanner(System.in);
        int number = reader.nextInt();
        Person[] per = new Person[number];    //初始化对象数组
        for(int i=0; i<per.length; i++) {    //经过循环输入
            String name = reader.next();
            int age = reader.nextInt();
            boolean genter = reader.nextBoolean();
            per[i] = new Person(name,age,genter);
        }
        for(int x=per.length-1; x>=0;x--){    
            per[x].toString();
        }
        
        per.toString();
        @SuppressWarnings("unused")
        Person s = new Person();
    }

}
View Code

 

覆盖:

输入:

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.util.Arrays;
import java.util.Objects;
import java.util.Scanner;

class PersonOverride{
    private String name;
    private int age;
    private boolean gender;

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

    @Override
    public boolean equals(Object obj){
        if (this == obj){
            return true;
        }
        if(obj == null)
        {
            return false;
        }
        if (this.getClass() != obj.getClass()){
            return false;
        }
        PersonOverride p = (PersonOverride)obj;
        boolean b1 = Objects.equals((this.name), p.name);
        boolean b2 = (this.age == p.age);
        boolean b3 = (this.gender == p.gender);
        if(b1 && b2 && b3){
            return true;
        }
        return false;
    }

    public PersonOverride(String _name, int _age, boolean _gender){
        name = _name;
        age = _age;
        gender = _gender;
    }
    public PersonOverride(){
        this("default",1,true);
    }
}

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int n1 = scanner.nextInt();
        PersonOverride[] persons1 = new PersonOverride[n1];
        for (int i = 0; i < n1; i++) {
            persons1[i] = new PersonOverride();
        }
        int n2 = scanner.nextInt();
        scanner.nextLine();
        PersonOverride[] persons2 = new PersonOverride[n2];
        for (int i = 0; i < n2; i++) {
            String str = scanner.nextLine();
            String[] arr = str.split("\\s+");
            PersonOverride temp = new PersonOverride(arr[0],Integer.parseInt(arr[1]),Boolean.valueOf(arr[2]));
            boolean flag = true;
            for (int j = 0; j < n2; j++) {
                if(temp.equals(persons2[j])){
                    flag = false;
                }
            }
            if(flag){
                persons2[i] = new PersonOverride(arr[0],Integer.parseInt(arr[1]),Boolean.valueOf(arr[2]));
            }
        }
        for (int i = 0; i < n1; i++) {
            System.out.println(persons1[i]);
        }
        int i,count = 0;
        for (i = 0; i < n2; i++) {
            if(persons2[i] == null){
                continue;
            }
            count++;
            System.out.println(persons2[i]);
        }
        System.out.println(count);
        System.out.println(Arrays.toString(PersonOverride.class.getConstructors()));
    }
}
法一
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
        Scanner in=new Scanner(System.in);
        int count=0;
        int n1=in.nextInt();
        ArrayList<PersonOverride> person1=new ArrayList<>();//ArrayList是集合+这是无参的
                                                            //<里面是类名> 后面是集合名
        while(n1-->0) {
            PersonOverride b=new PersonOverride();//建立一个对象
            person1.add(b);                       //加到集合里面去
            System.out.println(b.toString());
        }

        int n2=in.nextInt();
        ArrayList<PersonOverride> persons2=new ArrayList<>();
        while(n2-->0)
        {
            PersonOverride a= new PersonOverride(in.next(),in.nextInt(),in.nextBoolean());//有参的加入到对象里面去
            if(!persons2.contains(a))//判断集合里面是否含有该对象
            {
                persons2.add(a);//若是没有就加入到集合里
                System.out.println(a.toString());
            }
        }
        System.out.println(persons2.size());//集合的对象的数量
        System.out.println(Arrays.toString(PersonOverride.class.getConstructors()));
    }

}
class PersonOverride{
    private String name;
    private int age;
    private boolean gender;
    public PersonOverride(){
        this.name="default";
        this.age=1;
        this.gender=true;
    }
    //顺序必定要对。先写无参,而后写有参
    //构造方法要加public
    public PersonOverride(String name,int age,boolean gender){
        this.name=name;
        this.age=age;
        this.gender=gender;
    }
    //tostring方法直接用source
    @Override
    public String toString() {
        return name + "-" + age + "-" + gender;
    }
    //对于equals方法比较什么就打勾
    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + age;
        result = prime * result + (gender ? 1231 : 1237);
        result = prime * result + ((name == null) ? 0 : name.hashCode());
        return result;
    }
    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        PersonOverride other = (PersonOverride) obj;
        if (age != other.age)
            return false;
        if (gender != other.gender)
            return false;
        if (name == null) {
            if (other.name != null)
                return false;
        } else if (!name.equals(other.name))
            return false;
        return true;
    }
    //get和set若是前面的变量是私有的,那么久必定要加上
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    public boolean isGender() {
        return gender;
    }
    public void setGender(boolean gender) {
        this.gender = gender;
    }
    
    
    
}
法二

 

集体评分:

 

输入:

1 2 4 6 9

输出:

4.00

代码:

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int[] grade = new int[5];
        for(int i=0; i<grade.length; i++){
            grade[i] = in.nextInt();
        }
        RR rr = new RT(grade);
        double dd = rr.mark();
        System.out.printf("%.2f",dd);
    }
}
abstract class RR{
    int[] grade;
    public RR(int[] grade){
        this.grade = grade;
    }
    public abstract double mark();
}
class RT extends RR{
    public RT(int[] grade) {
        super(grade);
    }
    public double mark(){
        int max = 0, min = 0;
        int sum=0;
        for(int i=1; i<grade.length-1; i++){
            sum += grade[i];
        }
        double av = sum/3;
        return av;
    }
}
View Code

 

程序改错题2:

 

代码:

public class Main {
    public static void main(String[] args) {
        Animal animal = new Dog();
        animal.shout();
        animal.run();
    }
}

class Animal {
    void shout() {
        System.out.println("animal shout!");
    }
    void run() {
    }
}

class Dog extends Animal {
    void shout() {
        super.shout();
        System.out.println("wangwang……");
    }
    void run() {
        System.out.println("Dog is running");
    }
}
View Code

 

求某位同窗的平均分:

输入:

tom 78 99 98
mary 88 99 98 97

输出:

tom:91
mary:95

代码:

import java.util.Scanner;

public class Main {
    public static void main(String[]args){
        Scanner sc = new Scanner(System.in);
        String s1 = sc.next();
        int x1 = sc.nextInt();
        int x2 = sc.nextInt();
        int x3 = sc.nextInt();
        String ss1 = sc.next();
        int xx1 = sc.nextInt();
        int xx2 = sc.nextInt();
        int xx3 = sc.nextInt();
        int xx4 = sc.nextInt();
        System.out.println(s1+":"+getAvg(s1, x1, x2, x3));
        System.out.println(ss1+":"+getAvg(ss1, xx1, xx2, xx3, xx4));
    }
    public static int getAvg(String name, int... scores){
        int sum=0;
        for(int i:scores){
            sum += i;
        }
        int avg = sum/scores.length;
        return avg;
    }

}
View Code

 

统计符合条件元素的个数:

输入:

5

输出:

1,0

代码:

import java.util.Scanner;

public class Main {
        public static void main(String[] args)
        {
            Scanner in = new Scanner(System.in);
            int n = in.nextInt();
            int count1 = 0;
            int count2 = 0;
            for(int i=1; i <= n;i++){
                if (i%3 == 0){
                    count1 ++;
                }
                if(i%3 == 0 && i%2 == 0){
                    count2 ++;
                }
            }
            System.out.println(count1-count2+","+count2);
        }
}
View Code

 

判断闰年:

输入:

100

输出:

no

代码:

import java.util.Scanner;

public class Main {
    public static void main(String[] args){
        Scanner in = new Scanner(System.in);
        int n = in.nextInt();
        if(n%400 == 0 || (n%4==0&&n%100!=0))
        {
            System.out.println("yes");
        }
        else {
            System.out.println("no");
        }
    }
}
View Code

 

求一个三位正整数各位数字之和:

输入:

678

输出:

21

代码:

//package 实验一;

import java.util.Scanner;

public class Main {
    public static void main(String []args){
        Scanner in = new Scanner(System.in);
        int n = in.nextInt();
        int sum = n/100 + n/10%10 + n%10;
        System.out.println(sum);
    }
}
View Code

 

计算钱币:

输入:

47.63

输出:

4 张十元
1 张五元
2 张一元
1 个五角
1 个一角
1 个贰分
1 个壹分

代码:

//package 实验一;

import java.util.Scanner;

public class Main {
    public static void main(String[] args){
        Scanner in =new Scanner (System.in);
        double n=in.nextDouble();
        int m;
        n= n*100;
        m=(int)n;
        System.out.println(m/1000+"张十元");
        System.out.println(m%1000/500+"张五元");
        System.out.println(m%500/100+"张一元");
        System.out.println(m%100/50+"个五角");
        System.out.println(m%50/10+"个一角");
        System.out.println(m%10/2+"个贰分");
        System.out.println(m%2+"个壹分");
    }
}
View Code

 

以英里计的平均速度:

输入:

45 30 14

输出:

11.54

代码:

import java.util.Scanner;

public class Main {
    public static void main(String[]args){
        Scanner in=new Scanner(System.in);
        int m=in.nextInt();
        int s=in.nextInt();
        int d=in.nextInt();
        double time=(double)(m/60.0+s/3600.0);
        double v = (double)(d/time/1.6);
        System.out.print(String.format("%.2f",v));
    }
}
View Code

 

点是否在圆内:

输入:

4 5

输出:

1

代码:

import java.util.Scanner;

public class Main {
    public static void main(String[]args){
        Scanner in = new Scanner(System.in);
        int x = in.nextInt();
        int y = in.nextInt();
        if((x*x + y*y) < 100){
            System.out.println("1");
        }
        else {
            System.out.println("0");
        }
    }
}
View Code

 

计算工资数:

输入:

40

输出:

800

代码:

import java.util.Scanner;

public class Main {
    public static void main(String[]args){
        Scanner in = new Scanner(System.in);
        int n = in.nextInt();
        if(n < 0){
            System.out.println(0);
        }
        else if(n <= 120){
            System.out.println(n*20);
        }
        else{
            System.out.println(120*20 + (n-120)*40);
        }
    }
}
View Code

 

闰年判断:

输入:

2013

输出:

no

代码:

import java.util.Scanner;

public class Main {
    public static void main(String[] args){
        Scanner in = new Scanner(System.in);
        int n = in.nextInt();
        if((n%4==0 && n%100!=0) || n%400==0){
            System.out.println("yes");
        }
        else{
            System.out.println("no");
        }
    }
}
View Code

 

成绩分级管理:

输入:

72

输出:

C

代码:

import java.util.Scanner;

public class Main {
    public static void main(String[]args){
        Scanner in = new Scanner(System.in);
        int n = in.nextInt();
        if(n<60){
            System.out.println("E");
        }
        else if(n>=60&&n<70){
            System.out.println("D");
        }
        else if(n>=70&&n<80){
            System.out.println("C");
        }
        else if(n>=80&&n<90){
            System.out.println("B");
        }
        else{
            System.out.println("A");
        }
    }
}
View Code

 

判断三角形类型:

 

 

代码:

import java.util.Scanner;
public class Main{
     public static void main(String[] args)
     {
       Scanner sc=new Scanner(System.in);
       double a=sc.nextDouble();
       double b=sc.nextDouble();
       double c=sc.nextDouble();
       if(a<1||a>200||b<1||b>200||c<1||c>200)
       {System.out.println("Wrong Format");}
       else
       {
         if(a+b>c&&a+c>b&&b+c>a){
            if((a==b)&&(a==c))
                  {System.out.println("Equilateral triangle");}
            else if((a==b||a==c||b==c)&&(a*a+b*b-c*c<0.01||a*a+c*c-b*b<0.01||b*b+c*c-a*a<0.01))
                  {System.out.println("Isosceles right-angled triangle");}
            else if((a==b)||(a==c)||(b==c))
                  {System.out.println("Isosceles triangle");}
           else if(a*a+b*b-c*c<0.01||a*a+c*c-b*b<0.01||b*b+c*c-a*a<0.01)
                  {System.out.println("Right-angled triangle");}
            else
                  {System.out.println("General triangle");}
             }
        else 
            {System.out.println("Not a triangle");}
        }
      }
}
View Code

 

水仙花数:

 输入:

3

输出:

153
370
371
407

代码:

import java.util.Scanner;
import java.lang.Math;

public class Main {
    public static void main(String[]args){
        Scanner in = new Scanner(System.in);
        int n = in.nextInt();
        int head = (int)Math.pow(10, n-1);
        int tail = (int)Math.pow(10, n);
        int arr[] = new int[10];
        for(int i=0;i<arr.length;i++){
            arr[i] = (int)Math.pow(i, n);
        }
        for (int i=head; i<tail; i++){
            int temp = i;
            int sum = 0;
            while(temp!=0){
                sum += arr[temp % 10];
                temp /= 10;
            }
            if(sum == i){
                System.out.println(i);
            }
        }
    }
}
View Code

 

统计正数和负数的个数而后计算这些数的平均值:

 输入:

1 2 -1 3 0

输出:

3
1
5
1.25

代码:

import java.util.Scanner;

public class Main {
    public static void main(String[]args){
        Scanner in = new Scanner(System.in);
        int zhengshu = 0;
        int fushu = 0;
        int sum = 0;
        while(true){
            int n = in.nextInt();
            if(n == 0){
                break;
            }
            if(n > 0){
                zhengshu ++;
            }
            else
                fushu ++;
            sum += n;
        }
        if(zhengshu + fushu != 0){
            System.out.println(zhengshu);
            System.out.println(fushu);
            System.out.println(sum);
            double average = 0.0;
            average = 1.* sum / (fushu + zhengshu);
            System.out.println(average);
        }
    }
}
View Code

 

阶乘计算:

 输入:

10

输出:

3628800

代码:

import java.math.BigDecimal;
import java.util.Scanner;

public class Main {
    public static void main(String[]args){
        Scanner in = new Scanner(System.in);
        int n = in.nextInt();
        BigDecimal a = new BigDecimal("1");
        for(int i=1; i<=n; i++){
            a = a.multiply(BigDecimal.valueOf(i));
        }
        System.out.println(a);

    }
}
View Code

 

最大因子:

 

 

 代码:

import java.util.Scanner;

public class Main {
    public static void main(String[]args){
        Scanner in = new Scanner(System.in);
        int n = in.nextInt();
        for(int i = n-1; i>=1; i--){
            if(n % i == 0){
                System.out.println(i);
                break;
            }
        }
    }
}
View Code

 

职工排序题:

 输出:

编号,团险,个险,姓名,性别
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) throws InterruptedException {
        Scanner sc = new Scanner(System.in);
        List<Staff> ss=new ArrayList<Staff>();
        ss.add(new Staff(1,500,400,"职工1","female"));
        ss.add(new Staff(2,400,600,"职工2","female"));
        ss.add(new Staff(3,600,300,"职工3","male"));
        ss.add(new Staff(4,800,200,"职工4","female"));
        ss.add(new Staff(5,500,700,"职工5","male"));

        Collections.sort(ss);
        System.out.println("编号,团险,个险,姓名,性别");
        for (Staff s:ss){
            System.out.println(s.toString());
        }
        ss.sort(new newComparetor());
        System.out.println("编号,团险,个险,姓名,性别");
        for (Staff s:ss){
            System.out.println(s.toString());
        }


    }
}

class Staff implements Comparable<Staff>{
    private int number;
    private int tscore;
    private int pscore;
    private String name ;
    private String sex;

    public Staff() {
    }

    public Staff(int number, int tscore, int pscore, String name, String sex) {
        this.number = number;
        this.tscore = tscore;
        this.pscore = pscore;
        this.name = name;
        this.sex = sex;
    }

    public int getNumber() {
        return number;
    }

    public void setNumber(int number) {
        this.number = number;
    }

    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;
    }

    public int getTscore() {
        return tscore;
    }

    public void setTscore(int tscore) {
        this.tscore = tscore;
    }

    public int getPscore() {
        return pscore;
    }

    public void setPscore(int pscore) {
        this.pscore = pscore;
    }

    @Override
    public int compareTo(Staff s) {
        int ret=this.pscore+this.tscore-s.getPscore()-s.getTscore();
        if (ret>0)ret=1;
        else if (ret<0)ret=-1;
        return ret;
    }

    @Override
    public String toString() {
        return number +
                "," + tscore +
                "," + pscore +
                "," + name +
                "," + sex;
    }
}

class newComparetor implements Comparator<Staff> {
    public newComparetor() {
    }

    @Override
    public int compare(Staff o1, Staff o2) {
        int ret=o1.getTscore()-o2.getTscore();
        if (ret>0)ret=1;
        else if (ret<0)ret=-1;
        return ret;
    }
}
View Code

 

数组元素的删除:

输入:

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.Scanner;
import java.util.LinkedList;

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(" ");
            }
        }    
    }
}
View Code

 

使用二维数组实现Matrix(矩阵):

输入1:

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

输出1:

28 14 
79 44 

输入2:

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

输出2:

28 14 
79 44 

代码:

import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
        Scanner input=new Scanner(System.in);
        int m,n,q;
        m=input.nextInt();
        n=input.nextInt();
        int a[][]=new int[m][n];
        for(int i=0;i<m;i++)
            for(int j=0;j<n;j++)
                a[i][j]=input.nextInt();
        
        n=input.nextInt();
        q=input.nextInt();
        int b[][]=new int[n][q];
        for(int i=0;i<n;i++)
            for(int j=0;j<q;j++)
                b[i][j]=input.nextInt();
        int c[][]=new int[a.length][b[0].length];
        jzmultiply (a ,b);
        
    }
    public static int[][] creatjz ()
    {
        Scanner scan=new Scanner(System.in);
        int a = scan.nextInt();
        int b = scan.nextInt();
        int[][] jz = new int[a][b];
        int i,j;
        
        for(i=0;i<a;i++)
        {
            for(j=0;j<b;j++)
            {
                jz[i][j]=scan.nextInt();
            }
        }
        return jz;
    }
    
    public static void jzmultiply (int[][] a ,int[][] b)
    {
        int[][] sum = new int [a.length][b[0].length];
        int i, j, k;
        
        for(i = 0; i < a.length; i++ )
        {
            for(j = 0; j < b[0].length; j++)
            {
                for(k = 0;k < b.length; k++)
                {
                    sum[i][j] =sum[i][j] + a[i][k] * b[k][j];
                }
                 
            }
        }
        printjz(sum,a.length,b[0].length);
    }
     public static void printjz(int[][] sum,int m,int q)
    {
         int i, j;
         for( i=0; i<m; i++)
         {
             for( j=0; j<q; j++)
            {
                 System.out.print(sum[i][j]+" ");
             }//必需要带括弧啊,一句话也要带
           System.out.println();    
         }
        }
    
}
View Code

 

数组乱炖:

输入:

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

输出:

[2, 1, 3, 5, 6]
[2, 1, 3, 5, 6]
[1, 2, 3, 5, 6]
no
[9, 9, 3, 5, 6]
no
[4, 3, 7, 6, 8]
[4, 3, 7, 6, 8]
[3, 4, 6, 7, 8]
3
[9, 9, 6, 7, 8]
no

代码:

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();
        if (n>0){
            int[] a=new int[n];
            int[] b=new int[n];
            for (int i = 0; i < n; i++) {
                a[i]= sc.nextInt();
            }
            System.out.println(Arrays.toString(a));
            System.arraycopy(a, 0, b, 0, a.length);
            System.out.println(Arrays.toString(b));
            Arrays.sort(a);
            System.out.println(Arrays.toString(a));
            int m= Arrays.binarySearch(a,sc.nextInt());//这里不能使用顺序查找
            if(m>-1) System.out.println(m);//下标有效则找到
            else System.out.println("no");
            if (n>=2){
                a[0]=9;
                a[1]=9;
            }
            System.out.println(Arrays.toString(a));
            if (Arrays.equals(a,b)) System.out.println("yes");
            else System.out.println("no");
        }
    }
}
View Code

 

求矩阵主对角线元素的和:

输入:

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

输出:

34.5

代码:

import java.util.*;

public class Main{
    public static void main(String args[]) {
        Scanner sc = new Scanner(System.in);
        int n=sc.nextInt();
        double[][] a=new double[n][n];
        double s=0;
        for(int i=0;i<n;i++)
        {
            for(int j=0;j<n;j++)
            {
                double t=sc.nextDouble();
                if(i==j)
                    s+=t;
            }
        }
        System.out.println(s);
    }
}
非满分题解

 

学术会议地点统计问题:

输入:

z:bj 3,hz 2,qd 4,nj 5,wh 3,bj 3
w:hn 7,xm 6,bj 4,gz 6,wh 4

输出:

z:bj 6,w:wh 4

代码:

// package 实验四;

import java.util.*;

public class Main {
    public static void main(String[] args){
        Scanner sc=new Scanner(System.in);
        StringBuilder sb=new StringBuilder();
        TreeMap<String,Integer> tm2=getMap(sc.nextLine());//tm2是z教授
        TreeMap<String,Integer> tm1=getMap(sc.nextLine());//tm1是w教授
        Set<String> strings1 = tm1.keySet();
        Set<String> strings2 = tm2.keySet();
        for (String string : strings1) {
            if (strings2.contains(string)){
                int num1=tm1.get(string);
                int num2=tm2.get(string);
                if (num1>num2){
                    sb.append("w:").append(string).append(" ").append(num1).append(",");
                }else{
                    sb.append("z:").append(string).append(" ").append(num2).append(",");
                }
            }
        }
        if (sb.toString().equals("")) System.out.println("none");
        else{
            String[] split = sb.toString().split(",");
            for (int i = 0; i < split.length; i++) {
                System.out.print(split[i]);
                if (i!=split.length-1) System.out.print(",");
            }
        }
        sc.close();
    }

    public static TreeMap<String,Integer> getMap(String s){
        TreeMap<String,Integer> tm2=new TreeMap<>();
        String sss= s.replace(","," ");
        String[] ss=sss.split(":");
        String[] s1 = ss[1].split(" ");
        for (int i1 = 0; i1 < s1.length; i1+=2) {
            if (tm2.get(s1[i1])!=null){
                tm2.put(s1[i1], tm2.get(s1[i1])+Integer.parseInt(s1[i1+1]));
            }else{
                tm2.put(s1[i1],Integer.parseInt(s1[i1+1]));
            }
        }
        return tm2;
    }
}
View Code

 

学生成绩读取与排序:

输入:

小明,2001,Java,88
小刚,2002,Java,78
小丁,2003,Java,56
小宏,2004,Java,85
小明,2001,Python,84
小刚,2002,Python,98
小丁,2003,JavaWeb,66
小宏,2004,Algorithm,87
exit

输出:

No1:2002,小刚
No2:2001,小明
No3:2004,小宏
No4:2003,小丁

代码:

// package 实验四;
// 
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Scanner;

class student implements Comparable<student>{
    String name;
    String id;
    int sum;
    double avg;
    int cnt;

    @Override
    public int compareTo(student o) {
        student one = (student) o;
        if(this.sum-one.sum!=0)
            return (int)(one.sum-this.sum);
        else
            return this.id.compareTo(one.id);
    }
}
public class Main {
    public static void main(String[] args) {
        Scanner cin = new Scanner(System.in);
        ArrayList<student> a = new ArrayList<>();
        HashMap<String,Integer> m = new HashMap<>();
        int cnt = 0;
        while(true){
            String s = cin.nextLine();
            if(s.equals("exit"))       break;
            s = s.trim();
            String [] t = s.split(",");
            int x = Integer.parseInt(t[3]);
            if(m.containsKey(t[1])){
                int id = m.get(t[1]);
                a.get(id).sum += x;
                a.get(id).cnt++;
                a.get(id).avg = 1.0*a.get(id).sum/a.get(id).cnt;
            }
            else{
                m.put(t[1],cnt);
                student st = new student();
                st.sum = x; st.id = t[1];
                st.name = t[0];st.cnt = 1;
                st.avg = 1.0*st.sum/st.cnt;
                a.add(st);
                cnt++;
            }
        }
        Collections.sort(a);
        for(int i = 0;i < a.size();i++){
            System.out.printf("No%d:%s,%s\n",i+1,a.get(i).id,a.get(i).name);
        }
    }
}
View Code

 

字符串集合求并集:

输入:

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) {
        Scanner sc=new Scanner(System.in);
        String s=sc.nextLine();
        String[] str=s.split(" ");
        TreeSet ts1=new TreeSet();
        TreeSet ts2=new TreeSet();
        for(int i=0;i<str.length;i++){
            if(ts1.size()<5){
                ts1.add(str[i]);
            }else if(ts2.size()<5){
                ts2.add(str[i]);
            }
        }
        ts1.addAll(ts2);//交集后赋给ts1
        Iterator it=ts1.iterator();
        while(it.hasNext()){
            System.out.println(it.next());
        }
    }
}
法一
import java.util.Scanner;
import java.util.TreeSet;

public class Main {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        TreeSet<String> s1 = new TreeSet<String>();//默认字典序
        TreeSet<String> s2 = new TreeSet<String>();
        String str = sc.nextLine();
        String[] s = str.split(" ");
        for(int i=0;i<s.length;i++) {
            if(s1.size()!=5) {
                s1.add(s[i]);
            }else if(s2.size()!=5){
                s2.add(s[i]);
            }else {
                break;
            }
        }
        s1.addAll(s2);
        for(String ss:s1) {
            System.out.println(ss);
        }
    }
}
法二

 

GeneralStack:

输入:

Integer
5
2
1 2 3 4 5
Double
5
3
1.1 2.0 4.9 5.7 7.2
Car
3
2
1 Ford
2 Cherry
3 BYD
quit

输出:

Integer Test
push:1
push:2
push:3
push:4
push:5
pop:5
pop:4
[1, 2, 3]
sum=6
interface GeneralStack
Double Test
push:1.1
push:2.0
push:4.9
push:5.7
push:7.2
pop:7.2
pop:5.7
pop:4.9
[1.1, 2.0]
sum=3.1
interface GeneralStack
Car Test
push:Car [id=1, name=Ford]
push:Car [id=2, name=Cherry]
push:Car [id=3, name=BYD]
pop:Car [id=3, name=BYD]
pop:Car [id=2, name=Cherry]
[Car [id=1, name=Ford]]
Ford
interface GeneralStack

代码:

// package 实验四;

import java.util.ArrayList;
import java.util.Scanner;
 
interface GeneralStack<T>{
    public T push(T item);            //如item为null,则不入栈直接返回null。
    public T pop();                 //出栈,如为栈为空,则返回null。
    public T peek();                //得到栈顶元素,如为空,则返回null.
    public boolean empty();//如为空返回true
    public int size();     //返回栈中元素数量
}
class ArrayListGeneralStack implements GeneralStack{
    ArrayList list=new ArrayList();
    @Override
    public String toString() {
        return  list.toString();
    }
 
    @Override
    public Object push(Object item) {
        if (list.add(item)){
            return item;
        }else {
            return false;
        }
    }
 
    @Override
    public Object pop() {
        if (list.size()==0){
            return null;
        }
        return list.remove(list.size()-1);
    }
 
    @Override
    public Object peek() {
        return list.get(list.size()-1);
    }
 
    @Override
    public boolean empty() {
        if (list.size()==0){
            return true;
        }else {
            return false;
        }
    }
 
    @Override
    public int size() {
        return list.size();
    }
}
class Car{
    private int id;
    private String name;
 
    @Override
    public String toString() {
        return "Car [" +
                "id=" + id +
                ", name=" + name  +
                ']';
    }
 
    public int getId() {
        return id;
    }
 
    public void setId(int id) {
        this.id = id;
    }
 
    public String getName() {
        return name;
    }
 
    public void setName(String name) {
        this.name = name;
    }
 
    public Car(int id, String name) {
        this.id = id;
        this.name = name;
    }
}
public class Main {
    public static void main(String[] args) {
        Scanner sc=new Scanner(System.in);
        while (true){
            String s=sc.nextLine();
            if (s.equals("Double")){
                System.out.println("Double Test");
                int count=sc.nextInt();
                int pop_time=sc.nextInt();
                ArrayListGeneralStack arrayListGeneralStack = new ArrayListGeneralStack();
                for (int i=0;i<count;i++){
                    System.out.println("push:"+arrayListGeneralStack.push(sc.nextDouble()));
                }
                for (int i=0;i<pop_time;i++){
                    System.out.println("pop:"+arrayListGeneralStack.pop());
                }
                System.out.println(arrayListGeneralStack.toString());
                double sum=0;
                int size=arrayListGeneralStack.size();
                for (int i=0;i<size;i++){
                    sum+=(double)arrayListGeneralStack.pop();
                }
                System.out.println("sum="+sum);
                System.out.println("interface GeneralStack");
            }else if (s.equals("Integer")){
                System.out.println("Integer Test");
                int count=sc.nextInt();
                int pop_time=sc.nextInt();
                ArrayListGeneralStack arrayListGeneralStack = new ArrayListGeneralStack();
                for (int i=0;i<count;i++){
                    System.out.println("push:"+arrayListGeneralStack.push(sc.nextInt()));
                }
                for (int i=0;i<pop_time;i++){
                    System.out.println("pop:"+arrayListGeneralStack.pop());
                }
                System.out.println(arrayListGeneralStack.toString());
                int sum=0;
                int size=arrayListGeneralStack.size();
                for (int i=0;i<size;i++){
                    sum+=(int)arrayListGeneralStack.pop();
                }
                System.out.println("sum="+sum);
                System.out.println("interface GeneralStack");
            }else if (s.equals("Car")){
                System.out.println("Car Test");
                int count=sc.nextInt();
                int pop_time=sc.nextInt();
                ArrayListGeneralStack arrayListGeneralStack = new ArrayListGeneralStack();
                for (int i=0;i<count;i++){
                    int id=sc.nextInt();
                    String name=sc.next();
                    Car car = new Car(id,name);
                    System.out.println("push:"+arrayListGeneralStack.push(car));
                }
                for (int i=0;i<pop_time;i++){
                    System.out.println("pop:"+arrayListGeneralStack.pop());
                }
                System.out.println(arrayListGeneralStack.toString());
                if (arrayListGeneralStack.size()>0){
                    int size=arrayListGeneralStack.size();
                    for (int i=0;i<size;i++){
                        Car car=(Car) arrayListGeneralStack.pop();
                        System.out.println(car.getName());
                    }
                }
                System.out.println("interface GeneralStack");
            }else if (s.equals("quit")){
                break;
            }
        }
 
    }
}
 
View Code