Last active
January 7, 2017 12:27
-
-
Save mokomokohitsuzi/baa611c6d0ae1b9821dd80540b9eeef0 to your computer and use it in GitHub Desktop.
新・明解Java入門 演習7-8
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* a以上b未満の乱数を生成して、その値を返却するメソッド【int random(int a,int b)】を | |
* 作成せよ。内部で乱数を生成する標準ライブラリを呼び出すこと。 | |
* なお、bの値がaより小さい場合には、aの値をそのまま返却すること。 | |
*/ | |
package hukusyuu.en07; | |
import java.util.Random; | |
import java.util.Scanner; | |
public class En07_08 { | |
public static void main(String[] args) { | |
Scanner stdIn = new Scanner(System.in); | |
System.out.println("a以上b未満の乱数を生成します。"); | |
System.out.print("整数a:"); | |
int a = stdIn.nextInt(); | |
System.out.print("整数b:"); | |
int b = stdIn.nextInt(); | |
System.out.println(); | |
// bがaよりも小さい場合はaの値を返却 | |
if (b < a) { | |
System.out.println(a); | |
} else { | |
int random = random(a, b); | |
System.out.println(random); | |
} | |
} | |
static int random(int a, int b) { | |
// Ramdom変数をメソッド内部で呼び出し | |
Random rand = new Random(); | |
// a以上b未満の乱数の作成は、 | |
// 乱数をb-aの範囲で作成し、その後aを+する。 | |
int random = rand.nextInt(b - a) + a; | |
return random; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment