我的计划有问题。
import java.util.*;
public class P1D{
public static void main (String args[]) {
boolean error = false;
String randString;
int i = 0;
System.out.println("Number|Power|Between");
for(i = 1; i <= 10; i++)
{
int number = i; //numbers 1-10
int numbersq = (int)(Math.pow(i, 2)); //square of numbers
Random rand = new Random();
int random = (rand.nextInt(numbersq) + (number - 1)); //random number between number & square (inclusive)
if (number == 1) //prevents random from being over 1
{
random = 1;
}
if (random > numbersq || random < number) //if random is out of bounds, displays an error
{
//error = true;
randString = (String.valueOf(random) + " <-- ERROR");
} //notifies me of errors if random is out of bounds
else //if no error, random isn't changed and error=false
{
error = false;
randString = String.valueOf(random);
}
System.out.println(number + "\t" + numbersq + "\t" + randString);
}
if ( error = false )
{
System.out.println("all good in the hood");
}
else
{
System.out.println("Something went wrong");
}
}
}
该计划旨在:
问题是随机数通常高于或低于限制(不是很多),并且检查错误的布尔值总是表示存在错误,即使没有错误。
有人可以提供有关如何补救随机限制和布尔问题的建议吗?
答案 0 :(得分:2)
尝试此解决方案 - 它符合您的所有要求
import java.util.*;
public class P1D{
public static void main (String args[]) {
boolean error = false;
String randString;
System.out.println("Number|Power|Between");
for(int i = 1; i <= 10; i++)
{
int numbersq = i*i; //square of numbers
Random rand = new Random();
//random number between number & square (inclusive)
int random = (rand.nextInt((numbersq - i) + 1) + i);
//prevents random from being over 1
if (i == 1)
random = 1;
//if random is out of bounds, displays an error
if (random > numbersq || random < i) {
error = true;
randString = (String.valueOf(random) + " <-- ERROR");
}
//notifies me of errors if random is out of bounds
//if no error, random isn't changed and error=false
else {
error = false;
randString = String.valueOf(random);
}
System.out.println(i + "\t" + numbersq + "\t" + randString);
}
if (!error) {
System.out.println("all good in the hood");
} else {
System.out.println("Something went wrong");
}
}
}
数|电源|
之间1 1 1
2 4 3
3 9 9
4 16 10
5 25 11
6 36 29
7 49 24
8 64 35
9 81 75
10 100 52
引擎盖上的一切都很好