[Detailed + super basic] Java-study notes 03

One, Scanner

1. Guide package (idea automatic guide package) import java.util.Scanner;

2. Create

Class name object name = new class name ();

Scanner sc =new Scanner(System.in);

System.in represents input from the keyboard

3. Use

Object name. Member method name ()

Get an int number entered by the keyboard: int num =sc.nextInt();

Get a string entered on the keyboard: String str=sc.next();

Two, Random

1. Guide package (idea automatically guide package) import java.utilRanom()

2. Create

Class name object name = new class name ();

Random r=new Random();

3. Use

Get a random int number (the range is all ranges of int, there are positive and negative two): int num=r.nextInt()

Get a random int number (the parameter represents the range, left closed and right open interval): int num=r.nextInt(a) //represents the generation of random numbers in [0,a)

code show as below:

package 小练习;

import java.util.Random;

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

import java.util.Random;

public class random01 {
    public static void main(String[] args) {
        Random r =new Random();
        int num=r.nextInt(5);
        String [] name =new String[]{"吕布", "关羽", "张飞", "赵云", "孙不坚"};
        System.out.println("出战武将是"+name[num]);
    }
}

Three, guess the number game

Ideas:

1. First, you need to generate a random number, and once it does not change, use Random's nextInt method

2. We need our keyboard to input numbers, using Sanner's nextInt method

3. Judge the relationship between the two numbers and give feedback

code show as below:

package 小练习;

import java.util.Random;
import java.util.Scanner;

public class caishuzi{
    public static void main(String[] args) {
        Random r = new Random();
        int randomNUM = r.nextInt(100) + 1;
        Scanner sc = new Scanner(System.in);
        while (true){
            System.out.println("请你输入你猜测的数字:");
            int guessNUM = sc.nextInt();//你猜测的数字
            if (guessNUM > randomNUM) {
                System.out.println("太大了,请重试");
            } else if (guessNUM < randomNUM) {
                System.out.println("太小了,请重试");
            } else {
                System.out.println("恭喜你,答对了");
                break;
            }
        }
    }
}

Guess you like

Origin blog.csdn.net/qq_51808107/article/details/113064460