Java common knowledge points - keyboard input, random number generation, obtaining system time

Note: Most of the following content is compiled by me, and the source is marked below.

Paste an example code first:


/*
 * 例子说明:随记获取10个随记加法算式,要求用户输入答案,程序判断正确与否,并记录答题时间
 */
import java.util.Calendar;
import java.util.Date;
import java.util.Scanner;

public class s3_6 {
    public static void main(String[] args) {
        int[] add1=new int[10];
        int[] add2=new int[10];
        int[] result=new int[10];
        int score=0;

        Scanner sc=new Scanner(System.in);  //获取输入操作    
        //获取测试开始时间
        Date timeBefore=new Date();  
        long start=timeBefore.getTime();

        for (int i = 0; i < 5; i++) {
            //随记生成1-15的正整数加数
            add1[i]=(int)(Math.random()*15+1);
            add2[i]=(int)(Math.random()*15+1);
            System.out.print(add1[i]+"+"+add2[i]+"=");
            //对输入答案操作进行异常判断
            try {
                result[i]=sc.nextInt();
            } catch (Exception e) {
                System.out.println("你的输入有问题,请出入数字。");
                return;
            }
            if(result[i]==(add1[i]+add2[i])) {
                score++;
                System.out.println("正确");
            }
            else
            {
                System.out.println("错误");
            }
        }
        //获取测试结束时间
        Date timeAfter=new Date();
        long end=timeAfter.getTime();
        System.out.println("你最终得分是:"+score);
        System.out.println("所花时间为:"+(double)(end-start)/1000);
    }
}

Generation of random numbers

There are three methods for generating random numbers in Java:

  1. Use System.currentTimeMillis() to get a long number of the current time in milliseconds.
  2. Returns a double value between 0 and 1 via Math.random().
  3. Use the Random class to generate a random number. This is a professional Random tool class with powerful functions.
The first

Get random numbers through System.currentTimeMillis(). In fact, it is to get the current time in milliseconds, which is of type long. The method of use is as follows:

final long l = System.currentTimeMillis();

To get an integer of type int, just convert the above result to type int. For example, get an int between [0, 100). Methods as below:

final long l = System.currentTimeMillis();
final int i = (int)( l % 100 );
Type 2

Get random numbers through Math.random(). In fact, it returns a double value between 0 (inclusive) and 1 (exclusive). The method of use is as follows:

final double d = Math.random();

To get an integer of type int, just convert the above result to type int. For example, get an int between [0, 100). Methods as below:

final double d = Math.random();
final int i = (int)(d*100);
Type 3

Use the Random class to get random numbers.

The usage is as follows:
(01) Create a Random object. There are two ways to create a Random object, as follows:

Random random = new Random();//默认构造方法
Random random = new Random(1000);//指定种子数字

(02) Obtain random numbers through the Random object. The random value types supported by Random include: boolean, byte, int, long, float, double.
For example, get an int between [0, 100). Methods as below:

int i2 = random.nextInt(100);

The above detailed explanation of random numbers is referred to ( http://www.cnblogs.com/skywang12345/p/3341423.html )

Three ways to enter a value with the keyboard

Method 1: Receive a character from the console and print it

import java.io.*;
public static void main(String [] args) throws IOException{ 
         System.out.print("Enter a Char:"); 
         char i = (char) System.in.read(); 
         System.out.println("your char is :"+i); 
} 

Although this method realizes the acquisition of the input characters from the keyboard, System.out.read() can only acquire one character. At the same time, the type of the variable acquired can only be char. When we enter a number, we hope to get When it is also an integer variable, we have to modify the variable type, which is more troublesome.

Method 2: Receive a string from the console and print it out. In this topic, we need to use the BufferedReader class and the InputStreamReader class

import java.io.*;
public static void main(String [] args) throws IOException{ 
           BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); 
           String str = null; 
           System.out.println("Enter your value:"); 
           str = br.readLine(); 
           System.out.println("your value is :"+str); 
}

This way we can get the string we entered.

Method 3: I think this method is the simplest and most powerful, that is to use the Scanner class

import java.util.Scanner;
public static void main(String [] args) { 
         Scanner sc = new Scanner(System.in); 
         System.out.println("请输入你的姓名:"); 
         String name = sc.nextLine(); 
         System.out.println("请输入你的年龄:"); 
         int age = sc.nextInt(); 
         System.out.println("请输入你的工资:"); 
         float salary = sc.nextFloat(); 
         System.out.println("你的信息如下:"); 
         System.out.println("姓名:"+name+"\n"+"年龄:"+age+"\n"+"工资:"+salary); 
}

This code has shown that the Scanner class can achieve its function with only a small change, whether it is for string or integer data or float type variables! Undoubtedly he is the most powerful!
The above is taken from ( http://blog.sina.com.cn/s/blog_93dc666c0101h00f.html )

Get system time

a) Using Date, get the current time: Date date = new Date(); Result: Thu May 11 11:30:25 CST 2017

b) Using Calendar, since the Calendar class is an abstract class and the constructor of the Calendar class is protected, it is not possible to use the constructor of the Calendar class to create objects. The API provides the getInstance() method to create objects.

public static void main(String[] args) {  
    Calendar calendar = Calendar.getInstance();  
    Date time = calendar.getTime();  
    System.out.println(time);  
    long timeInMillis = calendar.getTimeInMillis();  
    System.out.println(timeInMillis);  
}  

result:

Thu May 11 18:03:00 CST 2017  
1494496980905  

2. About the conversion of time format:
It is very important for us to obtain the time of the system, and the conversion format is very important to us. If we need any time format, we can use the SimpleDateFormat class to convert it into the required format:

public static void main(String[] args) {          
    Date date = new Date();    
       System.out.println(date);    
       SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");    
       String dateNowStr = sdf.format(date);    
       System.out.println("格式化后的日期:" + dateNowStr);  
       Calendar calendar = Calendar.getInstance();  
       calendar.add(Calendar.DAY_OF_MONTH, 3);//正数可以得到当前时间+n天,负数可以得到当前时间-n天  
       date = calendar.getTime();  
       System.out.println("获取当前时间未来的第三天:" + date);  
       calendar.setTime(date);  
    String time = sdf.format(date);  
    System.out.println("格式化获取当前时间未来的第三天:" + time);  
}  

result:

Thu May 11 18:15:29 CST 2017  
格式化后的日期:2017-05-11  
获取当前时间未来的第三天:Sun May 14 18:15:29 CST 2017  
格式化获取当前时间未来的第三天:2017-05-14  

Excerpted from https://blog.csdn.net/zouxucong/article/details/71601740

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325927765&siteId=291194637