Java(NetBeans)中,如何求一个负数到一个正数之间的随机整数?
要求用户输入两个不同的数,然后求这两个数之间的随机整数列。
比如说,用户输入第一个数是10,第二个数是-3,就得到10 -3 8 5 2 1 9 -2 6 1 3 4 7 -1。
我自己编了一点,但是只能求两个正数之间的随机整数,如果输入负数,就不会输出。
[code=Java][/code]/*
*
*/
package 123;
import java.io.*;
public class 123 {
public static void main(String[] args) throws
IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
int num1 = 0;
int num2 = 0;
boolean stop1 = false;
boolean stop2 = false;
while (!stop1) {
try {
System.out.print("Enter a number: ");
num1 = Integer.parseInt(in.readLine());
stop1 = true;
} catch (
NumberFormatException nfe) {
System.out.println("Input is invalid.");
}
}
while (!stop2) {
try {
System.out.print("Enter a number: ");
num2 = Integer.parseInt(in.readLine());
if (num2 != num1) {
stop2 = true;
}
if (num2 == num1) {
System.out.println("Please enter an another number.");
}
} catch (NumberFormatException nfe) {
System.out.println("Input is invalid.");
}
}
int max = 0;
int min = 0;
if (num1 > num2) {
max = num1;
min = num2;
}
if (num2 > num1) {
max = num2;
min = num1;
}
int[] randArr = new int[max - min + 1];
for (int i = 0; i < randArr.length; i++) {
boolean used = true;
int r = 0;
while (used) {
r = (int) ((max - min + 1) * Math.random() + min);
used = false;
for (int j = 0; j < randArr.length; j++) {
if (randArr[j] == r) {
used = true;
}
}
}
randArr[i] = r;
}
for (int i = 0; i < randArr.length; i++) {
System.out.print(randArr[i] + " ");
}
}
}
------解决方案--------------------其实还可以换一个思路,你先生成这样一个数组
min,min+1,min+2,...,max-1,max
然后将他们的顺序打乱即可
------解决方案--------------------你的算法,有个问题,
Java code
for (int j = 0; j < randArr.length; j++)
{
if (randArr[j] == r)
{
used = true;
}
}