[Learning] Sannner Java classes and class Random

Scanner class

  1. Guide package:import java.util.Scanner;
  2. Create an object: Scanner 对象名称 = new Scanner(System.in); //System.in 表示从键盘上获取
  3. Use: Object members of the method name ();.

Exercises

Two input numbers, and the sum of two numbers

import java.util.Scanner;

public class Demo02ScannerSum {
   public static void main(String[] args) {
       Scanner sc = new Scanner(System.in);
       System.out.println("请输入第一个数字:");
       int num1 = sc.nextInt();
       System.out.println("请输入第二个数字:");
       int num2 = sc.nextInt();
       int sum = num1 + num2;
       System.out.println("两个数的和是:" + sum);
   }

}

Random category

  1. Guide package:import java.util.Random;
  2. Create an object: Random 对象名称 = new Random();
  3. Use: int have a random number (int ranges of all ranges, positive and negative):
    int num = r.nextInt();
    Gets a random number int (range parameter represents the left and right opening and closing section):
    int num = r.nextInt(3);
    actually represent: [0,3), i.e. 0 to 2;

Exercises

Small game viewing

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

public class Demo04RandomGame {
    public static void main(String[] args) {
        Random r = new Random();
        Scanner sc = new Scanner(System.in);
        int num = r.nextInt(101);			//[0~100]之间随机取一个数
        System.out.println("请输入数字:");
       	
        //使用while(ture)死循环,直到猜对结束
        while (true){
            int n=sc.nextInt();
            if(n>num){
                System.out.println("大了");
            }
            if (n < num){
                System.out.println("小了");
            }
            if (n == num){
                System.out.println("恭喜你,猜对了!");
                break;			//用break结束循环
            }
        }
    }
}

Released seven original articles · won praise 2 · Views 266

Guess you like

Origin blog.csdn.net/sy140823/article/details/104542260