I'm having an issue with my program.
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");
}
}
}
The program is intended to:
-List numbers 1-10 -Square the number -Print a random number between the original number and the square (inclusive)
The issue is that the random number is often above or below the limit (not by much) and the Boolean to check for errors always says that there is an error, even if there isn't one.
Can somebody offer advice on how to remedy the random limit and the Boolean issue?
Aucun commentaire:
Enregistrer un commentaire