Example explanation of random class and scanner class

王林
Release: 2020-01-17 17:04:21
forward
2050 people have browsed it

Example explanation of random class and scanner class

Generate a random number within the specified range

Math.random()Generate a random number, the random number is 0 Between 1 and 1, the type is double.

Code example:

public class randCase { public static void main(String[] args) { double rand = 0; for (int i = 0; i < 10; i++) { rand = Math.random(); System.out.println(rand); } } }
Copy after login

(Free learning video tutorial sharing:java video tutorial)

Read the string from the standard input and Integer (gets user input)

Scanner in = new Scanner(System.in)Connect to standard input.

where in represents a variable.

in.nextLine() can read a line of string from the command line.

in.nextInt() can read a positive integer from the command line.

The dot operator is an operator in Java. It is the same operator as the dot in System.out.printf() and Math.random(). It is used to dot the "variable" in front of the dot. "operation". The so-called "operation" refers to the method, which is the main method we have been writing. These operations are performed one by one. The method of use is called invoke a method.

import java.util.Scanner; tells the program where the Scanner type is.

Create a "variable" of Scanner type, its function is to help us read data from the standard input.

Code example:

import java.util.Scanner; // 告诉程序Scanner类型在哪 public class scannerCase { public static void main(String[] args) { // Scanner.nextLine(); 从命令行中读取一行字符串。 Scanner in = new Scanner(System.in); System.out.println("请输入一句话:"); String str = in.nextLine(); System.out.println(str); // Scanner.nextInt(); 从命令行中读取一行正整数。 System.out.println("请输入一个数字:"); int num = in.nextInt(); System.out.println(num); } }
Copy after login

The output result is as shown in the figure:

Example explanation of random class and scanner class

Recommended related articles and tutorials:java Quick Start

The above is the detailed content of Example explanation of random class and scanner class. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:cnblogs.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!