1. java.util.Random
이 Random().nextInt(int bound)는 0(포함)부터 경계(제외)까지 임의의 정수를 생성합니다.
(1) 코드 조각
getRandomNumberInRange(5, 10)의 경우 5(포함)에서 10(포함) 사이의 임의의 정수를 생성합니다.
private static int getRandomNumberInRange(int min, int max) { if (min >= max) { throw new IllegalArgumentException("max must be greater than min"); } Random r = new Random(); return r.nextInt((max - min) + 1) + min; }
(2)(max – min) + 1) + min은 무엇인가요?
위 수식은 min(포함)과 max(포함) 사이의 임의의 정수를 생성합니다.
//Random().nextInt(int bound) = Random integer from 0 (inclusive) to bound (exclusive) //1. nextInt(range) = nextInt(max - min) new Random().nextInt(5); // [0...4] [min = 0, max = 4] new Random().nextInt(6); // [0...5] new Random().nextInt(7); // [0...6] new Random().nextInt(8); // [0...7] new Random().nextInt(9); // [0...8] new Random().nextInt(10); // [0...9] new Random().nextInt(11); // [0...10] //2. To include the last value (max value) = (range + 1) new Random().nextInt(5 + 1) // [0...5] [min = 0, max = 5] new Random().nextInt(6 + 1) // [0...6] new Random().nextInt(7 + 1) // [0...7] new Random().nextInt(8 + 1) // [0...8] new Random().nextInt(9 + 1) // [0...9] new Random().nextInt(10 + 1) // [0...10] new Random().nextInt(11 + 1) // [0...11] //3. To define a start value (min value) in a range, // For example, the range should start from 10 = (range + 1) + min new Random().nextInt(5 + 1) + 10 // [0...5] + 10 = [10...15] new Random().nextInt(6 + 1) + 10 // [0...6] + 10 = [10...16] new Random().nextInt(7 + 1) + 10 // [0...7] + 10 = [10...17] new Random().nextInt(8 + 1) + 10 // [0...8] + 10 = [10...18] new Random().nextInt(9 + 1) + 10 // [0...9] + 10 = [10...19] new Random().nextInt(10 + 1) + 10 // [0...10] + 10 = [10...20] new Random().nextInt(11 + 1) + 10 // [0...11] + 10 = [10...21] // Range = (max - min) // So, the final formula is ((max - min) + 1) + min //4. Test [10...30] // min = 10 , max = 30, range = (max - min) new Random().nextInt((max - min) + 1) + min new Random().nextInt((30 - 10) + 1) + 10 new Random().nextInt((20) + 1) + 10 new Random().nextInt(21) + 10 //[0...20] + 10 = [10...30] //5. Test [15...99] // min = 15 , max = 99, range = (max - min) new Random().nextInt((max - min) + 1) + min new Random().nextInt((99 - 15) + 1) + 15 new Random().nextInt((84) + 1) + 15 new Random().nextInt(85) + 15 //[0...84] + 15 = [15...99] //Done, understand?
(3) 5(포함)에서 10(포함) 사이의 범위에 있는 10개의 임의 정수의 완전한 예를 생성합니다.
package com.mkyong.example.test; import java.util.Random; public class TestRandom { public static void main(String[] args) { for (int i = 0; i < 10; i++) { System.out.println(getRandomNumberInRange(5, 10)); } } private static int getRandomNumberInRange(int min, int max) { if (min >= max) { throw new IllegalArgumentException("max must be greater than min"); } Random r = new Random(); return r.nextInt((max - min) + 1) + min; } }
Output
7
6
10
8
9
5
7
10
8
5
2. Math.random()은 0.0부터 )까지의 값을 제공합니다. 1.0(제외)을 임의의 double 값으로 사용합니다.
(1)코드 조각. 1.2를 참조하면 거의 동일한 공식입니다.
(int)(Math.random() * ((max - min) + 1)) + min(2)은 16(포함)에서 20( 포함) 예.
package com.mkyong.example.test; public class TestRandom { public static void main(String[] args) { for (int i = 0; i < 10; i++) { System.out.println(getRandomNumberInRange(16, 20)); } } private static int getRandomNumberInRange(int min, int max) { if (min >= max) { throw new IllegalArgumentException("max must be greater than min"); } return (int)(Math.random() * ((max - min) + 1)) + min; } }
Output
171620
3 Java 8에는 새로운 메소드 java가 추가되었습니다. .util . Random
19
20
20
20
17
20
16
public IntStream ints(int randomNumberOrigin, int randomNumberBound) public IntStream ints(long streamSize, int randomNumberOrigin, int randomNumberBound)
이 Random.ints(int 원점, int 경계) 또는 Random.ints(int min, int max)는 원점(포함)에서 경계(제외)까지 임의의 정수를 생성합니다.
(1)코드 조각.
private static int getRandomNumberInRange(int min, int max) { Random r = new Random(); return r.ints(min, (max + 1)).findFirst().getAsInt(); }
(2) 33(포함)에서 38(포함) 범위에 있는 10개의 임의 정수의 완전한 예를 생성합니다.
package com.mkyong.form.test; import java.util.Random; public class TestRandom { public static void main(String[] args) { for (int i = 0; i < 10; i++) { System.out.println(getRandomNumberInRange(33, 38)); } } private static int getRandomNumberInRange(int min, int max) { Random r = new Random(); return r.ints(min, (max + 1)).limit(1).findFirst().getAsInt(); } }
Output
3435
373338
스트림 크기가 10인 33(포함) 및 38(제외) 범위의 임의 정수를 생성합니다. forEach를 사용하여 출력을 인쇄합니다.
37
34
35
36
37
(3) 참고용으로 추가하세요.
//Java 8 only new Random().ints(10, 33, 38).forEach(System.out::println);34
37
373434
35
36
33
37
34
위 내용은 Java에서 임의의 정수를 생성하는 방법의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

이 기사에서는 Java 프로젝트 관리, 구축 자동화 및 종속성 해상도에 Maven 및 Gradle을 사용하여 접근 방식과 최적화 전략을 비교합니다.

이 기사에서는 Maven 및 Gradle과 같은 도구를 사용하여 적절한 버전 및 종속성 관리로 사용자 정의 Java 라이브러리 (JAR Files)를 작성하고 사용하는 것에 대해 설명합니다.

이 기사는 카페인 및 구아바 캐시를 사용하여 자바에서 다단계 캐싱을 구현하여 응용 프로그램 성능을 향상시키는 것에 대해 설명합니다. 구성 및 퇴거 정책 관리 Best Pra와 함께 설정, 통합 및 성능 이점을 다룹니다.

이 기사는 캐싱 및 게으른 하중과 같은 고급 기능을 사용하여 객체 관계 매핑에 JPA를 사용하는 것에 대해 설명합니다. 잠재적 인 함정을 강조하면서 성능을 최적화하기위한 설정, 엔티티 매핑 및 모범 사례를 다룹니다. [159 문자]

Java의 클래스 로딩에는 부트 스트랩, 확장 및 응용 프로그램 클래스 로더가있는 계층 적 시스템을 사용하여 클래스로드, 링크 및 초기화 클래스가 포함됩니다. 학부모 위임 모델은 핵심 클래스가 먼저로드되어 사용자 정의 클래스 LOA에 영향을 미치도록합니다.


핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

AI Hentai Generator
AI Hentai를 무료로 생성하십시오.

인기 기사

뜨거운 도구

WebStorm Mac 버전
유용한 JavaScript 개발 도구

Dreamweaver Mac版
시각적 웹 개발 도구

PhpStorm 맥 버전
최신(2018.2.1) 전문 PHP 통합 개발 도구

맨티스BT
Mantis는 제품 결함 추적을 돕기 위해 설계된 배포하기 쉬운 웹 기반 결함 추적 도구입니다. PHP, MySQL 및 웹 서버가 필요합니다. 데모 및 호스팅 서비스를 확인해 보세요.

스튜디오 13.0.1 보내기
강력한 PHP 통합 개발 환경
