+ 2
How can i create a variable integer named X, range between ( - 100 to 1000)
3 Réponses
+ 4
No, you can't because range of variable is decided by type of compiler used (16 bit,32bit ,or 64bit).
+ 3
Do you mean create an int named x set to a random value between 100 - 1000?
import java.util.Random;
public class Program
{
public static void main(String[] args) {
int max = 1000;
int min = 100;
int n = new Random().nextInt(max - min) + min + 1;
System.out.println(n);
}
}
This should result in what you're looking for if that is the case.
Or better yet:
import java.util.concurrent.ThreadLocalRandom;
public class Program
{
public static void main(String[] args) {
int max = 1000;
int min = 100;
int n = ThreadLocalRandom.current().nextInt(min, max + 1);
System.out.println(n);
}
}
+ 3
No, you cannot define a new range for a variable.
However, you can use setters to simulate this manually.
Example/
class Program{
int x;
// my var
public void setX(int newX){
if (newX <= - 100)
x = - 100;
else if (newX >= 1000)
x = 1000;
else
x = newX;
}
}
Now if I changed the variables value:
setX(x - 10000);
// x = -100