012 corejava 前几章基础知识

来源:互联网 发布:郑州网络销售抓人 编辑:程序博客网 时间:2024/06/15 22:15

第一章介绍java语言的历史与特性,并没有什么深入的地方,

第二章介绍java环境的配置,使用命令行,ide,已经applet的使用,firefox不支持。

export JAVA_HOME=/home/wang/srccomputer/jdk1.8.0_111export PATH=${JAVA_HOME}/bin:${JAVA_HOME}/jre/bin:$PATHexport CLASSPATH=.:$CLASSPATH:${JAVA_HOME}/lib:${JAVA_HOME}/jre/lib

第三章 基本语法

This chapter shows you how the basic programming concepts such as data types, branches, and loops are implemented in java.

简单的例子

/** * This is the first sample program in Core Java Chapter 3 * @version 1.01 1997-03-22 * @author Gary Cornell */public class FirstSample{   public static void main(String[] args)   {      System.out.println("We will not use 'Hello, World!'");   }}

The String API

一个很重要的类。

First, construct an empty string builder:

StringBuilder builder = new StringBiuilder();
Each time you need to add another part, call the append method.

builder.append(ch);builder.append(str);
String completeString = builder.toString();

输入

Scanner in = new Scanner(System.in);

To read an integer, use the nextInt method.

int age = in.nextInt();

import java.util.Scanner;/** * Created by wang on 17-7-1. */public class InputTest {    public static void main(String[] args) {        Scanner in = new Scanner(System.in);        System.out.print("What is your name? ");        String name = in.nextLine();        System.out.print("How old are you? ");        int age = in.nextInt();        System.out.println("Hello, " + name + ". Next year, you'll be " + (age + 1));    }}

输出

What is your name? wangrl
How old are you? 25
Hello, wangrl. Next year, you'll be 26

You can use the static String.format method to create a formatted string without printing it:

String message = String.format("Hello, %s. Next year, you'll be %d", name, age);

打印日期

System.out.printf("%tc", new Date());
Sat Jul 01 23:46:33 CST 2017

c Complete date and time.

文件的输入输出

Scanner in = new Scanner(Paths.get("myfile.txt"), "UTF-8");
PrintWriter out = new Printer("myfile.txt", "UTF-8");

控制流

import java.util.Scanner;/** * Created by wang on 17-7-1. */public class Retirement {    public static void main(String[] args) {        Scanner in = new Scanner(System.in);        System.out.print("How much money do you need to retire? ");        double goal = in.nextDouble();        System.out.print("How much money do you need to retire? ");        double payment = in.nextDouble();        System.out.print("Interest rate in %:");        double interestRate = in.nextDouble();        double balance = 0;        int years = 0;        // update account balance while goal isn't reached        while (balance < goal) {            balance += payment;            double interest = balance * interestRate / 100;            balance += interest;            years++;        }        System.out.println("You can retire in " + years + " years.");    }}

How much money do you need to retire? 100
How much money do you need to retire? 10
Interest rate in %:10
You can retire in 7 years.

import java.util.Scanner;/** * Created by wang on 17-7-2. */public class LotteryOdds {    public static void main(String[] args) {        Scanner in = new Scanner(System.in);        System.out.print("How many members do you need to draw? ");        int k = in.nextInt();                System.out.print("What is the hightest number you can draw? ");        int n = in.nextInt();        int lotteryOdds = 1;        for (int i = 1; i <= k; i++) {            lotteryOdds = lotteryOdds * (n - i + 1) / i;        }        System.out.println("Your odds are 1 in " + lotteryOdds + ". Good luck!");    }}

How many members do you need to draw? 7
What is the hightest number you can draw? 51
Your odds are 1 in 115775100. Good luck!

超级大数

BigInteger a = BigInteger.valueOf(100);
lotteryOdds = lotteryOdds.multiply(BigInteger.valueOf(n - i + 1).divide(BigInteger.valueOf(i)));

数组

for each循环

for (int element : a)    System.out.println(element);

类的三种关系

1. dependence "uses-a" relationship. Thus, a class depends on another class if its methods use or manipulate objects of that class.

2. aggregation "has-a" relationship. Containment means that objects of class A contain objects of class B.

3. The inheritance, "is-a" relationship. a more special and a more general class.

类的构造

In Java, the value of any object variable is a reference to an object that is stored elsewhere. The return value of the new operator is also a reference.

A statement such as

Date deadline = new Date();

import java.time.DayOfWeek;import java.time.LocalDate;/** * Created by wang on 17-7-3. */public class CalenderTest {    public static void main(String[] args) {        LocalDate date = LocalDate.now();        int month = date.getMonthValue();        int today = date.getDayOfMonth();        date = date.minusDays(today - 1);        DayOfWeek weekday = date.getDayOfWeek();        int value = weekday.getValue();    // 1 = Monday, ... 7 = sunday        System.out.println("Mon Tue Wed Thu Fri Sat Sun");        for (int i = 1; i < value; i++) {            System.out.print("    ");        }        while (date.getMonthValue() == month) {            System.out.printf("%3d", date.getDayOfMonth());            if (date.getDayOfMonth() == today) {                System.out.print("*");            } else {                System.out.print(" ");            }            date = date.plusDays(1);            if (date.getDayOfWeek().getValue() == 1) System.out.println();        }        if (date.getDayOfWeek().getValue() != 1) System.out.println();    }}

输出:

Mon Tue Wed Thu Fri Sat Sun
                      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
 31

方法的几个作用

A method cannot modify a parameter of a primitive type(that is, numbers or boolean values).

A method can change the state of an object parameter.

A method cannot make an object parameter refer to a new object.

构造器知识

import java.util.Random;/** * Created by wang on 17-7-6. */public class Employee {    private static int nextId;    private int id;    private String name = "";    private double salary;    // static initialization block    static {        Random generator = new Random();        nextId = Math.abs(generator.nextInt());    }    // object initialization block    {        id = nextId;        nextId++;    }    // three overload constructors    public Employee(String n, double s) {        name = n;        salary = s;    }    public Employee(double s) {        // calls the Employee(String, double) constructor        this("Employee #" + nextId, s);    }    // the default constructor    public Employee() {        // name initialized to "" --see above        // salary not explicity set -- initialized to 0        // id initialized in initialization block    }    public String getName() {        return name;    }    public double getSalary() {        return salary;    }    public int getId() {        return id;    }}

import java.util.Random;/** * Created by wang on 17-7-6. */public class Employee {    private static int nextId;    private int id;    private String name = "";    private double salary;    // static initialization block    static {        Random generator = new Random();        nextId = Math.abs(generator.nextInt());    }    // object initialization block    {        id = nextId;        nextId++;    }    // three overload constructors    public Employee(String n, double s) {        name = n;        salary = s;    }    public Employee(double s) {        // calls the Employee(String, double) constructor        this("Employee #" + nextId, s);    }    // the default constructor    public Employee() {        // name initialized to "" --see above        // salary not explicity set -- initialized to 0        // id initialized in initialization block    }    public String getName() {        return name;    }    public double getSalary() {        return salary;    }    public int getId() {        return id;    }}
name=Harry,id=1531055212, salary=4000.0
name=Employee #1531055213,id=1531055213, salary=60000.0
name=,id=1531055214, salary=0.0

包的使用

package

All standard Java packages are inside the java and javax package hierarchies.


Instead, super is a special keyword that directs the compiler to invoke the superclass method.

Subclass Constructor

call the constructor of the Employee superclass.

this

recall that the this keyword has two meanings: to denote a reference to the implicit parameter and to call another constructor of the same class.

The fact that an object variable can refer to multiple actual types is called polymorhpism.


/** * Created by wang on 17-7-7. */public class ManagerTest {    public static void main(String[] args) {        // construct a Manager object        Manager boss = new Manager("Carl Cracker", 80000, 1987, 12,15);        boss.setBonus(5000);        Employee[] staff = new Employee[3];        staff[0] = boss;        staff[1] = new Employee("Harry Hacker", 50000, 1989, 10, 1);        staff[2] = new Employee("Tommy Tester", 40000, 1990, 3, 15);        for (Employee e : staff) {            System.out.println("name=" + e.getName() + ",salary=" + e.getSalary());        }    }}

import java.time.LocalDate;/** * Created by wang on 17-7-7. */public class Employee {    private String name;    private double salary;    private LocalDate hireday;    public Employee(String name, double salary, int year, int month, int day) {        this.name = name;        this.salary = salary;        hireday = LocalDate.of(year, month, day);    }    public String getName() {        return name;    }    public void setName(String name) {        this.name = name;    }    public double getSalary() {        return salary;    }    public void setSalary(double salary) {        this.salary = salary;    }    public LocalDate getHireday() {        return hireday;    }    public void raiseSalary(double byPercent) {        double raise = salary * byPercent / 100;        salary += raise;    }}

/** * Created by wang on 17-7-7. */public class Manager extends Employee{    private double bonus;    public Manager(String name, double salary, int year, int month, int day) {        super(name, salary, year, month, day);        bonus = 0;    }    public double getSalary() {        double baseSalary = super.getSalary();        return baseSalary + bonus;    }    public void setBonus(double b) {        bonus = b;    }}

name=Carl Cracker,salary=85000.0
name=Harry Hacker,salary=50000.0
name=Tommy Tester,salary=40000.0

原创粉丝点击