-4
import java.util.Scanner;
import java.util.Random;

public class Lab04b 
{       
    public static void main(String []args)
    {    
        Random generator = new Random (); 
        Scanner scan = new Scanner(System.in);

        int num1;
        int num2;
        int num3;

        System.out.println("Enter X:");
        num1 = scan.nextInt();

        System.out.println("Enter Y:");
        num2 = scan.nextInt();

        num3 = generator.nextInt(num2) + num1;
        System.out.println("3 random integers in the range " + num1 + ".." + num2 + " are: " + num3);
    }
}

x と y の範囲の間で 3 つのランダムな整数を取得する方法に行き詰まっています。Y は最大の整数です。

4

5 に答える 5

1

ドキュメントから

nextInt(int n)
Returns a pseudorandom, uniformly distributed int value between 0
(inclusive) and the specified value (exclusive), drawn from this
random number generator's sequence.

したがって、random.nextInt(Y) は数値 0..Y を返します。下限を正しく取得する方法が不足していると思います。

X + random.nextInt(YX) はトリックを行います。

于 2013-09-25T06:44:30.677 に答える
0
import java.util.Scanner;

public class GenerateRandomX_Y_numbers {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter the numbers x and y: ");
        int x = Math.abs(sc.nextInt()), y = Math.abs(sc.nextInt());//we need //non-negative integers, that is why we use here Math.abs. which means the //absolute value

        print3RandomNumbers_between_x_and_y(x, y);

    }

public static void print3RandomNumbers_between_x_and_y(int x, int y) {//here //I create a method with void type that takes two int inputs
    boolean isTrue = (x < y);//according to our conditions X should less //than Y

    if (isTrue) {//if the condition is true do => generate three int in the //range x .... y
        int rand1 = (int) (Math.random() * (y - x) + 1);// y - x means our //range, we then multiply this substraction by Math.random()
        int rand2 = (int) (Math.random() * (y - x) + 1);//the productof this //multiplication we cast to int type that is why we have 
        int rand3 = (int) (Math.random() * (y - x) + 1);//(int) before //(Math.random() * (y - x));

        System.out.println("rand1 = " + rand1);//
        System.out.println("rand2 = " + rand2);//
        System.out.println("rand3 = " + rand3);//here print our result

    } else
        System.out.println("Error input: X should be less than Y. Try it again!");//if the condition is not true, i mean if x is not less than or equal //to Y, print this message
}

}

于 2015-06-26T10:43:40.493 に答える