Some compilation questions in the third edition of Java Fundamentals

Chapter 1 (If it is useful, please give me a free like, I also want to be happy)

1. How to use Notepad to write a Hello World program, compile and run it in the command window, and output the results.

HelloWorld.java

 1 public class HelloWorld {

 2      public static void main(String[] args) {

 3 System.out.println(" This is the first Java program !");

 4      }

 5  }

Chapter two

1. Write a program to calculate the value of 1+3+…+99. The requirements are as follows:

(1) Use loop statements to implement traversal from 1 to 99
(2) During the traversal process, determine whether the current number is an odd number through conditions. If so, add it up, otherwise do not add it.

  1. public class getSum {
  2.     public static void main(String[] args) {
  3.         int sum = 0;
  4.         for (int i = 1; i < 100; i++) {
  5.             if (i % 2 != 0)
  6.                 sum += i;
  7.         }
  8.         System.out.println(sum);
  9.     }
  10. }

 2. Use the do... while loop statement to calculate the factorial of the positive number 5.

  1. public class Test {
  2.     public static void main(String[] args) {
  3.         int i = 1;
  4.         long sum = 1;
  5.         do {
  6.              sum *= i;
  7.              i++;
  8.         } while (i <= 5);
  9.               System.out.println(sum);
  10.     }
  11. }

third chapter

A company is recruiting. Recruited personnel need to fill in personal information, write a resume encapsulation class, and write tests. Resume class diagram and output effect

Example.java

class Resume {

    private String name;

    private String sex;

    private int age;

    public Resume(){

    }

    public Resume(String name,String sex,int age){

        this.name = name;

        this.sex = sex;

        this.age = age;

    }

    public String getName(){

        return name;

    }

    public String getSex(){

        return sex;

    }

    public int getAge(){

        return age;

    }

    public void introduce(){

       System.out.println(" Name : "+this.getName()+"\ nGender : "+this.getSex()+"\ nAge : "+this.getAge());

    }

}

public class Example{

     public static void main(String[] args){

         Resume re = new Resume("李思","",20);

         re.introduce();

     }

}

Chapter 4
 The employees of a company are divided into 5 categories. Each category of employees has a corresponding encapsulation class. The information of these 5 categories is as follows.
(1) Emplovee: This is the parent class of all employees.

①Attributes: employee's name, employee's birthday month
②Method: Salary int month) Determine salary based on parameter month. If an employee has a birthday in that month, the company will pay an additional 100 yuan.
(2) Salariedemployee: A subclass of Employee, employees who receive a fixed salary.
Attributes: Monthly salary
(3) Hourlyemployee: A subclass of Employee. Employees who are paid by the hour will be paid 1.5 times their salary for the portion of work exceeding 160 hours per month.
Attributes: hourly wage, number of hours worked per month.
(4) Salesemployee: A subclass of Employee, salesperson, salary is determined by monthly sales and commission rate.
Attributes: monthly sales, commission rate.
(5) Baseplussalesemploye: A subcategory of Salesemployee, a salesperson with a fixed base salary, base salary plus sales commission.
Attribute: Basic salary.
This question requires writing a program based on the above employee classification to achieve the following functions:
(1) Create Employee, create several different Employee objects, and print a certain user
(2) Each class is fully encapsulated and non-privatization is not allowed Attributes.

Employee.java

abstract class Employee{

    private String name; // Define name and privatize attributes

    private int month; // Define the birthday month and privatize the attribute

    public Employee(){} // parameterless constructor

    public Employee(String name,int month){ // Constructor with parameters

        this.name = name; // Initialize and assign a value to the attribute name

        this.month = month; // Initialize and assign a value to the attribute month

    }

    // Method to get attribute name

    public String getName(){

        return name; // return name attribute

    }

    // Method to get attribute month

    public int getMonth(){

        return month; // return month attribute

    }

    // Assign initial value to attribute name

    public void setName(String name){

        this.name = name; // Attribute name in this class

    }

    // Assign an initial value to the attribute month

    public void setMonth(int month){

        this.month = month; // Attribute month in this class

    }

    // Create a method getSalary() to calculate salary. The parameter month is the month. If the current month is the employee's birthday,         the reward is 100 yuan .

    public double getSalary(int month){

        double salary = 0; // Define salary variable

        // Determine whether the current month is      the employee 's birthday month, if so, reward 100 yuan

        if(this.month == month){

            salary = salary + 100;         

            return salary; // return salary salary

        }

    }

}

SalariedEmployee.java

class SalariedEmployee extends Employee{

    private double monthSalary; // encapsulate monthSalary attribute

    public SalariedEmployee(){} // No parameter constructor

    // Constructor method    with parameters   name, birthday , month,   monthly salary

    public SalariedEmployee(String name,int month,double monthSalary){

        super(name,month); // Call the parameterized constructor of the parent class

        this.monthSalary = monthSalary; // Initialize and assign a value to the attribute monthSalary

    }

    // Get the value of monthSalary

        public double getMonthSalary(){

        return monthSalary;

    }

    // Assign value to monthSalary

    public void setMonthSalary(double monthSalary){

        this.monthSalary = monthSalary;

    }

    // Override the method in the parent class

    public double getSalary(int month){

        double salary = monthSalary+super.getSalary(month); // Define salary variable

        return salary;   

    }

}

HourlyEmployee.java

class HourlyEmployee extends Employee{

    private double hourlySalary; // Define the hourly salary of the attribute hourlySalary

    private int hours; // Define the number of hours worked per month in the attribute hours

    public HourlyEmployee(){} // No parameter constructor

    // Constructor method with parameters   Parameters Name Birthday month   Salary per hour Number of hours worked per month 

    public HourlyEmployee(String name,int month,double hourlySalary,int             hours){

        super(name,month); // Call the parameterized constructor of the parent class    

        this.hourlySalary = hourlySalary; // Initialize and assign a value to the attribute hourlySalary

        this.hours = hours; // Initialize and assign a value to the attribute hours

    }

    public double getHourlySalary(){ // Get the value of hourlySalary

        return hourlySalary;

    }

    public int getHours(){ // Get the value of hours

        return hours;

    }

    // Define the set method to set the value of hourlySalary hours

    public void setHourlySalary(double hourlySalary){

        this.hourlySalary =hourlySalary;

    }

    public void setHourly(int hours){

        this.hours = hours;

    }

    // Override parent class method

    public double getSalary(int month){

        if(hours < 0){ // If the number of working hours is less than , the output data is wrong

        System.out.println(" Data error ");

        return 0;

        }  

        // For less than 160 hours , multiply the number of working hours per month by the hourly wage

        else if(hours <= 160)

            return hourlySalary*hours+super.getSalary(month);

        // Hours exceeding 160 hours are calculated as 1.5 times     

        else return hourlySalary*160+hourlySalary*1.5*(hours-                     160)+super.getSalary(month);

    }

}

SalesEmployee.java

class SalesEmployee extends Employee{

    private double sales; // Define sales sales

    private double rate; // Define commission rate rate

    public SalesEmployee(){}

    public SalesEmployee(String name,int month,double sales,double rate){

        super(name,month);

        this.sales = sales;

        this.rate = rate;

    }

    public double getSales(){

        return sales;

    }

    public double getRate(){

        return rate;

    }

    public void setSales(double sales){

        this.sales = sales;

    }

    public void setRate(double rate){

        this.rate = rate;

    }

    public double getSalary(int month){

        return this.getSales()*(1+this.getRate())+super.getSalary(month);

    }

}

BasePlusSalesEmployee.java

class BasePlusSalesEmployee extends SalesEmployee{

    private double baseSalary; // Define base salary baseSalary

    // No parameter constructor

    public BasePlusSalesEmployee(){}

    // Construction method with parameters

    public BasePlusSalesEmployee(String name,int month,double sales,double         rate,double baseSalary){

        super(name,month,sales,rate);

        this.baseSalary = baseSalary;

    }

    //The get/set method calls and sets private properties

    public double gatBaseSalary(){

        return baseSalary;

    }

    public void setBaseSalary(){

        this.baseSalary = baseSalary;

    }

    public double getSalary(int month){

        return baseSalary+super.getSalary(month);

    }

}

Test.java

// Define a test class

public class Test{

    public static void main(String[] args){

    // Declare an array of type Employee and create objects of different subtypes

    Employee[] employee = {new SalariedEmployee( "张三" ,1,6000),new HourlyEmployee( " 李四" ,2,50,180),new SalesEmployee( "王                   五" ,3,6500,0.15),new BasePlusSalesEmployee( "Zhao Liu" ,4,5000,0.15,2000)};

    // Print the salary of each employee

    for(int i = 0; i < employee.length ;i++)

        System.out.println(Math.round(employee[i].getSalary(10)));

    }

}   

Chapter 6

5. 1. Randomly generate 10 random positive integers from 0 to 100 each time.
2. Calculate the number of months and days 100 days from today, and format it into the format of ×××XYearXMonth×Day and print it out.
Tips:
(1) Call the add() method of the Calendar class to calculate the date 100 days later.
(2) Call the getTime() method of the Calendar class to return an object of Date type.
(3) Use the DateFormat object in FULL format and call the format() method to format the Date object.

1.

Example.java

  1. import java.util.Random;
  2. public class Example {
  3.     public static void main(String[] args) {
  4.         for(int i=0;i<10;i++){
  5.             System.out.println(new Random().nextInt(100));
  6.         }
  7.     }
  8. }

2.

Test.java

  1. import java.text.DateFormat;
  2. import java.util.Calendar;
  3. import java.util.Date;
  4. public class Test {
  5.     public static void main(String[] args) {
  6.         Calendar calendar = Calendar.getInstance();
  7.         calendar.add(Calendar.DATE, 100);
  8.         Date date = calendar.getTime();
  9.         DateFormat format = DateFormat.getDateInstance(DateFormat.FULL);
  10.         String string = format.format(date);
  11.         System.out.println(string);
  12.     }
  13. }

Chapter VII

5.
1. Write a program to add elements to the ArmsList collection, and then traverse and output these elements.

2. Please write the program according to the following requirements.
(1) Write a Student class, including name and age attributes, and providing a parameterized construction method.
(2) In the Snudent class, override the toString() method to output the values ​​of age and name.
(3) In the Student class, override the hashCode() and equals() methods.
The return value of .hshCode() is the sum of the hash value of name and age.
.equals() determines whether the name and age of the object are the same. If they are the same, it returns true, if they are different, it returns false.

4) Write a test class, create a HashSet<Student> object hs, and add multiple sat objects to hs. Assume that there are two Student objects that are equal. Output the HashSet collection and observe whether the Student object is added successfully.

                         

                               Example.java

  1. public class Example {
  2.     public static void main(String[] args) {
  3.         ArrayList list = new ArrayList<>();
  4.         list.add("a");
  5.         list.add("b");
  6.         list.add("c");
  7.         list.add("a");
  8.         for(Iterator it = list.iterator();it.hasNext();){
  9.             System.out.println(it.next());
  10.         }
  11.     }
  12. }

2.

Test.java

  1. import java.util.*;
  2. class Student {
  3.     private int age;
  4.     private String name;
  5.     public Student(int age, String name) {
  6.         this.age = age;
  7.         this.name = name;
  8.     }
  9.     public String toString() {
  10.         return age + ":" + name;
  11.     }
  12.     public int hashCode() {
  13.         return name.hashCode() + age;
  14.     }
  15.     public boolean equals(Object obj) {
  16.         if (this == obj)
  17.             return true;
  18.         if (!(obj instanceof Student))
  19.             return false;
  20.         Student stu = (Student) obj;
  21.         return this.name.equals(stu.name) && this.age == stu.age;
  22.     }
  23. }
  24. public class Test {
  25.     public static void main(String[] args) {
  26.         HashSet<Student> hs = new HashSet<Student>();
  27.         hs.add(new Student(18, "zhangsan"));
  28.         hs.add(new Student(20, "lisa"));
  29.         hs.add(new Student(20, "lisa"));
  30.         System.out.print

1.Java is an object-oriented language

2. The characteristics of Java language: simplicity, object-oriented, cross-platform, security, support for multi-threading, and distribution

3. The javac command is used to compile Java source files into .class files .

4. The cross-platform feature of the Java language is guaranteed by the Java virtual machine .

5. The running environment of the Java program is JRE .

1.Java program code must be placed in a class, and the class is defined using the class keyword.

2. There are three types of comments in Java, namely single-line comments, multi-line comments, and document comments .

3. In Java, the storage space occupied by the int type is 4 bytes.

4. An array is a container , and the minimum value is 0 .

5.

1. The three major characteristics of object-oriented are encapsulation, inheritance and polymorphism.

2. For classes, member methods and attributes, Java provides four types of access control permissions, namely private ,     ____default____ , protected and public . 3. Static methods must be modified using the ___static_____ keyword. 4.Class encapsulation refers to privatizing the attributes in the class when defining a class, that is, using the ___private_____ keyword to modify it. 5. When resolving name conflicts between member variables and local variables in Java, you can use the __this______ keyword.

3.Static methods must be modified using the ___static_____ keyword.

4.Class encapsulation refers to privatizing the attributes in the class when defining a class, that is, using the ___private_____ keyword to modify it. 5. When resolving name conflicts between member variables and local variables in Java, you can use the __this______ keyword.

1. In object-oriented, the mechanism for sharing attributes and operations between classes is called inheritance.

2. In the inheritance relationship, the subclass will automatically inherit the methods in the parent class, but sometimes it is necessary to make some modifications to the inherited methods in the subclass, that is, rewrite the methods of the parent class .

3. The final keyword can be used to modify classes, variables and methods. It has the meaning of "unchangeable" or "final".

4. If a class wants to implement an interface, you can use the keyword implements

5. If a class wants to implement an interface, then it needs to override all methods defined in the interface, otherwise the class must be defined as an abstract class

6. If a subclass wants to reference members of the parent class, it can use the keyword surper .

1 The RuntimeException class and its subclasses are used to represent runtime exceptions.

2. Exceptions are divided into two types, namely run-time exceptions and compile-time exceptions.

3. The throw keyword is used to declare an instance object that throws an exception in a method.

4. If a method wants to throw multiple exceptions, you can use the throws keyword and separate the multiple exceptions with commas.

5. Custom exceptions need to inherit Exception.

1. Three classes are defined in Java to encapsulate operations on strings, namely String , StringBuffer and StringBuilder.

2. The method used to obtain the length of a String in Java is Length() .

3. The class in Java used to format dates into strings is DateFormat .

4. The class used to generate random numbers in Java is Random located in the java.util package .

5. It is known that sb is an instance of StringBuffer, and the value of sb.toString() is "abcde", then after executing reverse(), the value of sb.toString() is edcba .

1. Collection is the parent interface of all single-column collections. It defines some methods common to single-column collections (List and Sat).

2. When using an Iterator to traverse a collection, you first need to call the hashNext() method to determine whether there is the next element.

If there is a next element, call the next() method to retrieve the element.

3. If you want to sort the objects in the TreeSot collection, you must implement the Comparable interface.

4. The elements in the Map collection all appear in pairs, and they all exist in a mapping relationship between Key and Value .

5. ArrayList internally encapsulates a variable-length array .

1. The role of generics is to support type parameterization. Type type generic

2. Generics can be used in the definition of classes, interfaces and methods, which are called generic classes, generic interfaces and generic methods respectively.

3. In Jaya programs, there are often methods with uncertain parameter types or return value types. Such methods are collectively called generic methods in Java .

4. There are two ways to define the implementation class of a generic interface. One is to explicitly give the generic type in the direct interface, and the other is to declare the generic type directly after implementation .

1. The advantage of the reflection mechanism is that it can dynamically create objects and compile them.

2. If you want to instantiate objects of other classes through the Class class, you can use the newInstance() method, but you must ensure

There is a parameterless constructor in the class being instantiated.

3. All methods in the two classes can be obtained through reflection. You need to use the Method class in the java.lang.reflect package.

4. In reflection operation, class information can be obtained through getDeclareFieds() . Method can obtain all properties in this class.

5. When the Java virtual machine loads a .class file, it will generate a Class object representative file, and class information can be obtained from this object.

1The I/O stream in Java can be divided into byte stream and character stream according to the different data transmitted.

2. The class in the java.io package that can be used to read characters directly from a file is Reader

3. The I/O system provides two buffered byte streams, namely BufferedInputStream and BufferedOutputStream.

4. The JDK provides two classes that can convert byte streams into character streams, namely InputStreamReader and OutputStreamWriter .

5.java.io.FileOutputStream is a subclass of OutputStream , which is a byte output stream for operating files.

1. The JDBC driver manager is responsible for registering specific JDBC drivers, mainly implemented through the java.sql.DriverManager class.

2. When writing a JDBC application, the specified database driver or class library must be loaded into the classpath .

The executeUpdate(String sql) method of 3Statement interface is used to execute ISERT, update and DELETE statements in SQL .

4. PreparedStatement is a sub-interface of Statement and is used to execute precompiled SQL statements.

5. A large number of getXxx() methods are defined in the ResultSet interface. You can use the index of the field to obtain the specified data. The index of the field is numbered starting from 1 .

1. The two ways to implement multi-threading are to inherit the Thread class and implement the Runnable interface.

2. The entire life cycle of a thread is divided into 5 stages, namely New state (New), Ready state (Runnable), Running state (Running) , Blocked state and Death state.

3. In the Thread class, the start() method is provided to start a new thread.

Method is used to start a new thread.

4. Executing the sleep() method allows the thread to sleep for a specified period of time.

5. The synchronized code block is modified with the synchronized keyword.

1. The network reference model based on TCP/IP is divided into 4 layers, namely link layer, network layer, transport layer and application layer .

2. When conducting network communication, the transport layer can use TCP or UDP .

3. TCP must be used when downloading files .

4.JDK provides the DatagramSocket class, which can send and receive data packets.

5. The JDK provides two classes for implementing TCP programs: one is the ServerSocket class, which is used to represent the server side; the other is the Socket class, which is used to

Guess you like

Origin blog.csdn.net/m0_63715487/article/details/126835299