07Scanner class, Random class, ArrayList class

day07Scanner class, Random class, ArrayList class

The first chapter API

Outline

  • API (Application Programming Interface), an application programming interface.
  • Java API programmer is a dictionary, is available to the JDK classes we use documentation. These classes encapsulate the underlying code that implements them, we do not care how these classes are implemented, only need to learn how to use these classes. So we can query the API way to learn Java classes offered, and learned how to use them.

API use steps

  1. Opens the help file.
  2. Click on display, find the index, see the input box.
  3. Whom are you calling? Input in the input box, then press Enter.
  4. Look at the package. java.lang class does not need conductivity in the package, other needs.
  5. Explained and illustrated look like.
  6. Learning constructor.
  7. Use member method.

Chapter 2 Scanner class

lang package does not guide the package

2.1 Scanner Function

Scanner class features: the keyboard may be implemented to import data into the program.

Reference types step 2.2

1. Package guide

格式:import 包路径.类名称;

If the target class you want to use, and under current class in the same package, you can not write omitted Herald statement.

Only Java.lang contents of the package do not need to guide package, other packages require an import statement;

For example:

Java.util.Scanner;

2. Create Object

Format: class name = new class name ();

For example

Scanner sc = new Scanner(System.in);

3. Call method

Format: Object members of the method name ();.

变量名.方法名();

For example:

int i = sc.nextInt();//接受一个键盘录入的整数
import java.util.Scanner;//1.导包

public class Demo01Scanner {
    public static void main(String[] args) {
     //2.创建
    //备注:System.in 代表从键盘输入       
Scanner sc = new Scanner(System.in);

        //3.获取键盘输入的int数字
        int num = sc.nextInt();
        System.out.println("输入的int数字是:"+num);

        //4.获取键盘上输入的字符串
        String str = sc.next();
        System.out.println("输入的字符串是:"+str);
    }
}

2.3 anonymous object

The standard format to create objects:
the class name of the object name = new class name ();

1. Concept

Anonymous Object: No object variable names.

Anonymous object is the only object on the right, with no name on the left and the assignment operator.

2. Format

new category name (parameter list);

For example:

new Scanner(System.in);

Note: Anonymous objects can only be used only once, next time then had to create a new object.
Suggested Use: determining if there is an object can only be used only once, you can use an anonymous object.

3. Using anonymous object as a method parameter

public static void main(String[] args){
    //普通方式
    Scanner sc = new Scanner(System.in);
    methodPanner(sc);
    
    //使用匿名对象来进行传参
    methodParam(new Scanner(Sysetm.in))
}

public static void methodParam(Scanner sc){
    int num = sc.nextInt();
    System.out.println("输入的是:"+num);
}

4 as a return value

public static void main(String[] args){
    //普通方式
    Scanner sc = getScanner();
}

public static Scanner getScanner(){
    //普通方法
    //Scanner sc = new scanner(System.in);
    //return sc;
    
    //匿名对象作为方法的返回值
    return new Scanner(System.in);
}

Chapter Random class (random number generation)

1. Role

Random used to generate a random number

2. Use the step

  1. Guide package

    import java.util.Random;
  2. create

    Random r = new Random();
  3. use

  4. Obtaining a random number int (int range range, both positive and negative): int num = r.nextInt ();

code show as below:

import java.util.Random;

public static void main(String[] args){
    Random r = new Rondom();
    
    int num = r.nextInt();
    System.out.println("随机数是:"+num);
}

3. Practice

Random number generator specified range

// Get a random number int (int range range, both positive and negative)
the Random R & lt new new = the Random ();

import java.util.Random;
public static void main(String[] args){
    Random r = new Random();
    
    for(int i = 0;i<100;i++){
         //快捷输入法r.nextInt(输入最大范围-1);
        int num = r.nextInt(0-10);//范围实际上是0-9
        System.out.println(num);
    }
}

Int // Get a random number (range parameter represents the left and right opening and closing)
int NUM = r.nextInt (. 3); // range (0,3) i.e. 0-2

import java.util.Random

public static void main(String[] args){
        Random r = new Random();
        
        int num = r.nextInt(biund:10);
        System.out.print("随机数是:"+num);
}

Guessing game, there are number of restrictions

public class Demo04RandomGame {
    public static void main(String[] args) {
        Random r = new Random();
        int randomNum = r.nextInt(100) + 1;
        Scanner sc = new Scanner(System.in);

       //while循环
       //int i = 0;
       //while(true)
       for (int i = 0;i <=5;i++) {
            System.out.println("请输入你猜测的数字:");
            int guessNum = sc.nextInt();//键盘输入猜测的数字

            if (i == 5) {
                System.out.println("Game over");
                break;
            }
            if (randomNum > guessNum) {
                System.out.println("太小了,请重试。");
            } else if (randomNum < guessNum) {
                System.out.println("太大了,请重试。");
            } else {
                System.out.println("恭喜你,猜对了。");
                    break;//如果猜中,不在重试,跳出循环
            }
        }
        System.out.println("游戏结束。");
    }
}

Chapter IV ArrayList class

4.1 introduced - an array of objects

Any data type can be used as the array element type
Title:
define an array, for storing three person object.

Array has a drawback: Once the program is running during creation, the length can not be changed

public class Demo01Array {

    public static void main(String[] args) {
        //首先创建一个长度为3的数组,里面用来存放Person类型的对象
        Person[] array =new  Person[3];

        Person one = new Person("迪丽热巴",3);
        Person two = new Person("古力娜扎",6);
        Person three = new Person("马尔扎哈",9);

        //将one当中的地址值赋值到数组的0号元素位置
        array[0] = one;
        array[1] = two;
        array[2] = three;

        System.out.println(one);//地址值
        System.out.println(two);//地址值
        System.out.println(three);//地址值


        System.out.println(array[1].getName());//古力娜扎
    }
}

4.2 ArrayList use

1. Role

The length of the array can not be changed.

ArrayList but the length may be set arbitrarily changed.

2. View class

java.util.ArrayList : The need to import after the import use.

PS:

: Indicates a data type, called generics.

E, taken from Element (elements) of the first letter. E occurrences, we use a data type can be replaced, that means we will store reference type elements.

code show as below:

ArrayList<String>;//全都是String类型字符串的数据

note:

Generics can only be a reference type, not a basic type.

3. Review the constructor

public ArrayList():构造一个内容为空的集合

The basic format:

//备注:从Java1.7后开始,右侧尖括号部分可以不写内容,
//1.7之前右侧需要写,两侧类型必须相同
ArrayList<String> list = new ArrayList<>();

4. Notes

For ArrayList collection is not directly address the value of print, but the content.

.Add through the object (); to add data

If the content is empty, get will be empty brackets.

code show as below:

import java.util.ArrayList;//导包

public static void main(String[] args){
    ArrayList<String> list = new ArrayList<>();
    Sysout.out.println(list);//[]
    list.add("马尔扎哈");
    System.out.println(list);//马尔扎哈
    
}

The common method

1. Add element

Note: For the ArrayList collection is, add add the action must succeed, so that may or may not return type.

But for other collections (future learning) for, add add actions are not necessarily successful.

//向集合中添加元素,参数类型和泛型一致。
public boolean add(E e);

2. Get element

//从集合中获取元素,参数是索引编号,返回值就是对应位置的元素
public E get(int index);

3. Removing elements

//从集合中删除元素,参数就是索引编号,返回值就是被删除掉的元素
public E remove(int index);

4. Get set length

//获取集合的尺寸长度,返回值是集合中包含元素的个数
public int size();

code show as below:

public class Demo03ArrayListMethod {
    public static void main(String[] args) {
        ArrayList<String> list = new ArrayList<>();
        System.out.println(list);

        //向集合中添加元素: add
        boolean success  = list.add("柳岩");
        System.out.println(list);
        System.out.println("添加的动作是否成功:"+success);//true

        list.add("迪丽热巴");
        list.add("古力娜扎");
        list.add("玛尔扎哈");
        list.add("霹雳克擦");
        System.out.println(list);

        //从集合中获取元素:get.索引值  从0开始
        String name = list.get(1);
        System.out.println(name);

        //从集合中删除元素:remove.索引值从0 开始
        String whoRemooved = list.remove(4);
        System.out.println("被删除的人是:"+whoRemooved);
        System.out.println(list);

        //获取集合的长度尺寸,也就是元素个数
        int size = list.size();
        System.out.println("集合的长度是:"+size);

    }
}

6. traverse the collection of

hot key:

Through the collection shortcuts: variable name .fori

public class Demo04ArrayListEach {
    public static void main(String[] args) {
        ArrayList<String> list = new ArrayList<>();
        list.add("迪丽热巴");
        list.add("古力娜扎");
        list.add("玛尔扎哈");

        //遍历集合  快捷键:变量名.fori
        for (int i = 0;i<list.size();i++){
            System.out.println(list.get(i));
        }

    }
}

4.3 storing basic data types

ArrayList object can not be stored basic types, you can only store a reference type data .

If you want to set AlistList which stores basic types of data, you must use the basic types of packaging (reference type, are located in the packaging bag java.long)

basic type Wrapper class special
byte Byte
short Short
int Integer
long Long
float Float
double Double
char Character
boolean Boolean

JDK1.5 + from the start, auto packing, unpacking automatically.

Autoboxing: basic types -> package type

Auto-unboxing: Package Type -> basic types

4.4 ArrayList practice

1. added to the set value

Title: generating a random integer between 1-33 6, added to the collection, and traverse

import java.util.ArrayList;//导包

public static void main(String[] args){
    ArrayList<Integer> list = new ArrayList<>();
    Random r = new Random();
    
    for(int i = 0;i<6;i++){
        int num = r.nxtInt(33) + 1;
        list.add(num);
    }
    for(int i = 0;i<list.size();i++){
        System.out.println(list.get(i));
    }
}

2. objects to the collection

Title: Custom four student objects, added to the combination and traverse

Class given to students

public static void main(String[] args){
    private String name;
    private int age;
    
    public Student(){
        
    }
    public Student(String name,int age){
        this.name = name;
        this.age = age;
    }
    public void setName(String name){
        this.name = name;
    }
    public String getName(){
        return name;
    }
    public void setAge(int age){
        this.age = age;
    }
    public int getAge(){
        return age;
    }
    
}
import java.
public static void main(String[] args){
    ArrayList<Student> list = new ArrayList<>();
    Student one = new Student("雷神",21);
    Student two = new Student("狼人",22);
    Student three = new Student("黑寡妇",23);
    Student four = new Student("蛇女",24);
    
    list.add(one);
    list.add(two);
    list.add(three);
    list.add(four);
    
    for(int i = 0;i<list.size();i++){
        Student stu = list.get(i);
        System.out.println("姓名:"+getName+",年龄:"+getAge);
    }
}

3. Print collection method

Title: Method defined in the specified printing format set (the ArrayList type as a parameter), except that {} from a set of spreading, using @ separate each element. Referring element format @ @ {element} element.

public static void main(String[] args){
    ArrayList<String> list = new ArrayList<>();
    list.add("张三丰");
    list.add("张无忌");
    list.add("陈真");
    list.add("李连杰");
    System.out.println(list);
    
}
/*
定义方法的三要素
返回值类型:没有结果  没有运算 只是打印 所以用void
方法名称:printArrayList
参数列表:ArrayList
*/
public static void printArryList(ArryList<String> list){
    System.out.print("{");
    for(int i = 0;i<list.size();i++){
       String name = list.get(i);
        if(i == list.size() - 1){
            System.out.print(name+"}");
        }else{
            System.out.print(name+"@");
        }
    }
    
}

4. A method of obtaining a collection of

Title: Get all the even elements defined methods (Arraylist type as the return value)

import java.util.ArrayList;
import java.util,Random;
public static void mian(String[] args){
    //定义一个大集合存入20个随机数字
    ArrayList<Integer> bigList = new ArrayList<>();
    Random r = new Random();
    for(int i = 0;i<20;i++){
        int num = r.nextInt(100) + 1;//范围1-100
        bigList.add(num);
    }
    ArrayList<Integer> smallList = getSmallList(bigList);
    System.out.println("偶数的个数是:"+smallList.size());
    for(int i = 0;i < smallList.size();i++){
        System.out.println(smallList(i));
    }
}
public static ArrayList<Integer> getSmallList(ArrayList bigList){
    //创建一个小集合,用来装偶数结果
      ArrayList<Integer> smallList = new ArrayList<>();
    for(int i = 0;i<bigList.size();i++){
      int num = bigList.get(i);
        if(num % 2 == 0){
            smallList.add(num);
        }
    }
}

Guess you like

Origin www.cnblogs.com/anke-z/p/12363992.html
Recommended