Basic usage of Scanner, Random, and ArrayList in Java--Case: Guess the number game/random roll call

Table of contents

1. Scanner

2. Random 

3. ArrayList

add element 

​Edit delete element 

other reference types

ArrayList sorting

 Case - guess the number


1. Scanner

A simple text scanner that can parse primitive types and strings using regular expressions.

ScannerBreaks its input into tokens using a delimiter pattern, which by default matches whitespace. The resulting tokens can then be converted to values ​​of different types using different next methods.

For example, the following code enables a user to read a number from System.in:

Scanner sc = new Scanner(System.in);

                int i = sc.nextInt();

The following code makes longthe type myNumbersassignable via an item in the file:

Scanner sc = new Scanner(new File("myNumbers"));

        while (sc.hasNextLong()) {

        long aLong = sc.nextLong();

}

Scanners can also use delimiters other than whitespace. Here is an example of reading several items from a string: 

public class Aa {
    public static void main(String[] args) {
        String input = "1 fish 2 fish red fish blue fish";
        Scanner s = new Scanner(input).useDelimiter("\\s*fish\\s*");
        System.out.println(s.nextInt());
        System.out.println(s.nextInt());
        System.out.println(s.next());
        System.out.println(s.next());
        s.close();
    }
}

The output is:

Steps for usage

The Scanner class is located in the java.util package and needs to be imported before use. The syntax is as follows:

import java.util.Scanner;

Construction method

 method

 

public class ScannerTest {
    public static void main(String[] args) {
        //1.定义扫描器用来扫描键盘的输入
        Scanner scanner = new Scanner(System.in);
        //2.打印输出一个提示信息
        System.out.println("请输入一个整数:");
        //3.使用扫描器对象获得键盘的输入
        int num = scanner.nextInt();
        //4.使用结果
        System.out.println("你输入的是:"+num);

    }
}

Keyboard output works as follows: 

 

2. Random 

Instances of this class are used to generate streams of pseudorandom numbers.

If two Randominstances , the same sequence of method calls is made on each instance, and they will generate and return the same sequence of numbers. To guarantee the implementation of this property, a specific algorithm is Randomspecified . For full portability of Java code, a Java implementation must have classes Randomuse all of the algorithms shown here. But subclasses of Randomclass to use other algorithms as long as they conform to the general contract of all methods.

RandomThe algorithm implemented by the class uses a protectedutility method that provides up to 32 pseudo-randomly generated bits per call.

Many applications will find Math.random()the method easier to use.

Steps for usage

The Random class is located in the java.util package and needs to be introduced before use. The syntax is as follows:

import java.util.Random;

Construction method:

         Pass in parameters to determine a seed to record, and the random numbers generated each time are the same.

public class RandomTest {
    public static void main(String[] args) {
        Random random = new Random(1);//不指定参数,表示每一次都会重新生成一个随机数,传入参数,确定一个种子来记录,每次生成的随机数是相同的
        int num = random.nextInt();
        System.out.println(num);
    
    }
}

 operation result:

         If no parameter is specified, it means that a random number will be regenerated every time.

public class RandomTest {
    public static void main(String[] args) {
        Random random = new Random();//不指定参数,表示每一次都会重新生成一个随机数,传入参数,确定一个种子来记录,每次生成的随机数是相同的
        int num = random.nextInt();
        System.out.println(num);
    
    }
}

 operation result:

 Subscript 0 starts with 5 lengths 0 1 2 3 4

public class RandomTest {
    public static void main(String[] args) {
        Random random = new Random();
        int num = random.nextInt(5);  //0 1 2 3 4
        System.out.println(num);
    }
}

 operation result:

method

3. ArrayList

The ArrayList class is an array that can be dynamically modified. The difference from ordinary arrays is that it has no fixed size limit, and we can add or delete elements. ArrayList inherits from AbstractList and implements the List interface, which is the implementation of variable-sized arrays of the List interface.

Each ArrayList instance has a capacity . The capacity refers to the size of the array used to store the elements of the list. It is always at least equal to the size of the list. As elements are added to the ArrayList, its capacity grows automatically.

Steps for usage

The ArrayList class is located in the java.util package and needs to be introduced before use. The syntax is as follows:

import java.util.ArrayList; // import the ArrayList class
 
ArrayList<reference data type> object name=new ArrayList<>(); // initialization 

For example: 


ArrayList<String> list=new ArrayList<>();

 Construction method

 method

add element 

import java.util.ArrayList;
 
public class ArrayListTest {
    public static void main(String[] args) {
        ArrayList list = new ArrayList();
        list.add("美乐蒂");
        list.add("布丁狗");
        list.add("HelloKitty");
        System.out.println(list);
    }
}

 You can also add elements by index

import java.util.ArrayList;
 
public class ArrayListTest {
    public static void main(String[] args) {
        ArrayList list = new ArrayList();
        list.add(0,"美乐蒂");
        list.add(1,"布丁狗");
        list.add(2,"HelloKitty");
        System.out.println(list);
    }
}

 The result of the operation is:


delete element 

To delete elements in ArrayList, you can use the remove() method:

import java.util.ArrayList;

public class ArrayListTest {
public static void main(String[] args) {
    ArrayList<String> list = new ArrayList<String>();
    list.add("美乐蒂");
    list.add("布丁狗");
    list.add("HelloKitty");
    list.add("玉桂狗");
    list.remove(2); // 删除索引为2的元素
    System.out.println(list);

    }
}

 The result of the operation is:

Use size() to calculate how many pieces of data there are

import java.util.ArrayList;

public class ArrayListTest {
public static void main(String[] args) {
    ArrayList<String> list = new ArrayList<String>();
    list.add("美乐蒂");
    list.add("布丁狗");
    list.add("HelloKitty");
    list.add("玉桂狗");
    System.out.println(list.size());

    }
}

  The result of the operation is:

other reference types

The elements in ArrayList are actually objects. In the above example, the elements of ArrayList are all of type String.

If we want to store other types, and <E> can only be a reference data type, then we need to use the wrapper class of the basic type.

The packaging class table corresponding to the basic type is as follows:

 In addition, BigInteger and BigDecimal are used for high-precision operations. BigInteger supports integers of arbitrary precision and is also a reference type, but they have no corresponding basic types.

rrayList<Integer> li=new Arraylist<>(); // store integer elements
ArrayList<Character> li=new Arraylist<>(); // store character elements

 The following uses ArrayList to store numbers (using Integer type):

import java.util.ArrayList;
 
public class ArrayListTest{
    public static void main(String[] args) {
        ArrayList<Integer> list= new ArrayList<Integer>();
        list.add(10);
        list.add(15);
        list.add(20);
        list.add(25);
        for (int i : list) {
            System.out.println(i);
        }
    }
}

Run as follows: 

ArrayList sorting

The Collections class is also a very useful class, located in the java.util package, which provides the sort() method to sort a character or numeric list.

The following example sorts alphabetically:

import java.util.ArrayList;
import java.util.Collections;  // 引入 Collections 类
 
public class ArrayListTest {
    public static void main(String[] args) {
        ArrayList<String> list = new ArrayList<String>();
            list.add("Hello Kitty");
            list.add("MyMelody");
            list.add("Pom Pom Purin ");
            list.add("Pachacco");
            list.add("ShimitsYuko");
        Collections.sort(list);  // 字母排序
        for (String i : list) {
            System.out.println(i);
        }
    }
}

The result of the operation is as follows: 

Others, you can try it yourself according to the method posted above.

The following is a case, let's take a look

 Case - guess the number

Randomly generate a number between 1-100, and then the user guesses the number. If the number is too large, it prompts that the guess is too large, and if it is too small, it prompts that the guess is small.

Define keyboard input and random numbers

        Scanner scanner = new Scanner(System.in);
        Random random = new Random();

 Set a number between 1-100

 int num = random.nextInt(100)+1;//生成0-99 再加1 1-100;

Set a total number of plays

int count = 1; //统计猜的总次数

 Use do while loop middle if judgment

 do {
            System.out.println("请输入你猜的数字: ");
            int input = scanner.nextInt();
            if (input > num) {
                System.out.println("猜大了!!");
            } else if (input < num) {
                System.out.println("猜小了!!");
            } else {
                System.out.println("恭喜你猜对了!!");
                break;
            }
            count++;
        }while (true);

If the guess is correct, print out the total number

  System.out.println("本次游戏共猜了" + count + "次。");

Overall code:

public class Test01 {
    public static void main(String[] args) {
        //使用Scanner和Random完成一个猜数字的小游戏:
        //随机生产一个1-100之间的数字,然后用户猜数字,大了提示猜大了,小了提示猜小了,猜对了则统计猜的次数

        Scanner scanner = new Scanner(System.in);
        Random random = new Random();

        int num = random.nextInt(100)+1;//生成0-99 再加1 1-100;
        int count = 1; //统计猜的总次数
        //使用死循环进行猜数字,直到猜对结束循环
        do {
            System.out.println("请输入你猜的数字: ");
            int input = scanner.nextInt();
            //判断输入的数字和随机生成的数字
            if (input > num) {
                System.out.println("猜大了!!");
            } else if (input < num) {
                System.out.println("猜小了!!");
            } else {
                System.out.println("恭喜你猜对了!!");
                //break循环结束
                break;
            }
            //次数+1
            count++;
        }while (true);
        System.out.println("本次游戏共猜了" + count + "次。");
    }
}

The result of the operation is as follows:  

Guess you like

Origin blog.csdn.net/weixin_67224308/article/details/128015606