Can't print a Random integer - java

I have just started learning Java. I was learning about "Randomization" from the "Kilobolt" tutorials. When I ran this code:
import java.util.Random;
public class Randomization {
public static void main (String[] args) {
Random rand = new Random();
rand.nextInt(11);
System.out.println(rand);
}
}
The console displayed:
java.util.Random#1888759
Is this supposed to happen? Or are there errors in my code?
( Sorry if i used any wrong terms in this question, I'm new to the website)

You're printing a reference to the object rand. You can either print out the random number like below:
public class Randomization {
public static void main (String[] args) {
Random rand = new Random();
System.out.println(rand.nextInt(11));
}
}
Or you can store it in an int before printing:
public class Randomization {
public static void main (String[] args) {
Random rand = new Random();
int randomNumber = rand.nextInt(11);
System.out.println(randomNumber);
}
}
Either should work fine.

It should be:
public class Randomization {
public static void main (String[] args) {
Random rand = new Random();
int randomNumber = rand.nextInt(11);
System.out.println(randomNumber);
}
}
Because you need to print the number. not the object of Random.

you are printing the object System.out.println(rand);
so you are getting this java.util.Random#1888759
try this way
System.out.println(rand.nextInt(11));
Full working code

Random rand = new Random();
this variable has been declared as a Object of Random.
however I'm pretty sure your intentions were to show the number that will be produced randomly.
To show it as a number, you have to declare the variable as an object of int.
to do that you can do :
Random rand = new Random();
int randomNumber = rand.nextInt(11);
hope this helps.

Related

Generating a random number that ends with a certain digit in Java

How does one generate a random number between 0 and 500 that ENDS WITH 5 in Java? I'm fairly new to programming.
See Java Generate Random Number Between Two Given Values
Generate a random number between 0(included) and 50(excluded), multiply it by 10 and add 5.
import java.util.Random;
public class RandomFive {
static Random rand = new Random();
public static int randomFive() {
return rand.nextInt(50) * 10 + 5;
}
public static int randomFiveFun() {
int randomFive = 0;
while ((randomFive = rand.nextInt(500)) % 10 != 5);
return randomFive;
}
public static int randomFivePresidentJamesKPolck() {
return (rand.nextInt(50) * 2 + 1 ) * 5;
}
public static void main(String[] args) {
System.out.printf("Normal: %3d\n", randomFive());
System.out.printf("Fun: %3d\n", randomFiveFun());
System.out.printf("PJKP: %3d\n", randomFivePresidentJamesKPolck());
}
}
As #Lino pointed out, it is a good practice to use new Random() only once during your application's lifetime or to use ThreadLocalRandom. Additionally, please consider https://stackoverflow.com/a/3532136/18980756.

User inputs specific set of number and random number from the set is outputted

I have a java code that randomizes a number from a specific set, i want to be able to have the user inputs the specific set such as: {1,6,400,500} and the output is randomized from these numbers, how would i do that?, here is the code i have:
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ThreadLocalRandom;
public class Randomizer {
public static void main(String[] args)
{
List<Integer> list = new ArrayList<>();
list.add(1);
list.add(24);
list.add(77);
list.add(90);
list.add(80);
list.add(1790);
Randomizer obj = new Randomizer();
int boundIndex = 3;
System.out.println(
obj.getRandomElement(list, boundIndex));
}
public int getRandomElement(List<Integer> list,
int bound)
{
return list.get(
ThreadLocalRandom.current().nextInt(list.size())
% bound);
}
}
You can use the Random java util:
public static void main(String[] args) {
List<Integer> list = new ArrayList<>();
list.add(1);
list.add(24);
list.add(77);
list.add(90);
list.add(80);
list.add(1790);
Random random = new Random();
int randomInt = list.get(random.nextInt(list.size()));
System.out.println("Random int from list = " + randomInt);
}

Java error in declaring array in random

import java.util.Random;
class random
{
public static void main(String[] args)
{
int n[];
Random rand=new Random();
for(int i=0;i<=10;i++)
{
int n[i]=rand.nextInt();
System.out.println("The random number is::"+n[i]);
}
}
}
This is the error i get while compiling:
I have no idea can anyone please help.
// first you need to declare the size for the n array
int n[] = new int [11]; // needs to be 11
Random rand=new Random();
for(int i=0;i<=10;i++)
{
n[i]=rand.nextInt(); // and then just assign
System.out.println("The random number is::"+n[i]);
}
but to be honest you do not even need this array in this code as it is not being re-used
More simpler would be
Random rand=new Random();
for(int i=0;i<=10;i++)
{
System.out.println("The random number is::" + rand.nextInt());
}
You need to initialize your array. See link for an example.
https://docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html
n = new int[11];
before the for loop should do it.
Thanks for the catch wombat
try this thing...
import java.util.Random;
class random
{
public static void main(String[] args)
{
int[] n= {1,2,3,4,5,6,7,8,9,10,11};
for(int i=0;i<=10;i++)
{
Random rand=new Random();
n[i]=rand.nextInt();
System.out.println("The random number is::"+n[i]);
}
}
}
First of all, suppose we want to use array we can use in two ways:
As a variable where you need to define fixed size first otherwise you will get ArrayIndexOutOfBoundsException:
int[] id = new int[size fo array];
example : -
`
import java.util.Random;
class random
{ public static void main(String[] args)
{
// here first you need to initilized the array with fixed sizea
int n[] = new int[11];
Random rand=new Random();
for(int i=0;i<=10;i++)
{
n[i]=rand.nextInt();
System.out.println("The random number is::"+n[i]);
}
}
}
`
As an Argument of the method where you need not define the fixed size:
the best example is a command line argument
For execution below code, you need to pass command line argument at runtime.
`
import java.util.Random;
class random
{
public static void main(String[] args)
{
System.out.println(args[0] + args[1]);
}
}
`

calculate number of occurrences in array in java

I want to calculate the number of occurences of a specific number I decide in my main method. Here is what I have to do :
• A function that fills the array with random numbers.
• A function that calculates the number of occurrences,this function may not do any input or output.
• The main function that asks the user for the number and present the result on the screen.
Here is my code in java :
import java.util.Random;
import java.util.Scanner;
public class Code {
public void calculate(int value) {
Code c = new Code();
int count=0;
for (int n=0; n<array.length; n++) { // the code does not recognize array
if (array[n]==value) { // the code does not recognize array
count++;
}
}
System.out.println(count);
}
public void addToArray() {
int k =0;
int [] array = new int[10];
int min=0;
int max=10;
int diff = max-min;
while (k<10) {
Random r = new Random();
int x = r.nextInt(diff);
array[k]=x;
k=k+1;
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("give your number");
Code c = new Code();
Scanner s = new Scanner(System.in);
int value = s.nextInt();
c.addToArray();
c.calculate(value);
}
}
The only thing I need help with is the calculate method ,, eclipse does not recognize array in the calculate method above ..
How to correct the calculate method to make it recognize array ?
thank you
Your array is limited to the scope of the method addToArray(). So, it will not be visible to other methods. You need to make it global. Then it will work.
Instead of declaring array in the method addToArray, declare it in your class, like:
public class Code {
int [] array = new int[10];
...
if using Java 8 you could update your calculate methode like this :
public void calculate(int value) {
System.out.println(Arrays.stream(array)
.filter(i -> i == value)
.count());
}
By adding this imports to your class :
import java.util.Arrays;
And like mentionned HackerDarshi declaring the attribut array as a member of your class

static Math.random change java

I don't have a problem anymore, However I want to understand the behaviour of some code. Initially I was generating some random numbers and somewhere in my code the Math.random was returning the same number for all iterations. I tried to create a minimal example with the following two Classes:
first Class:
public class randomTest {
public randomTest()
{ }
public double generateRandomNumber()
{
double r = Math.random();
return r;
}
public static void main(String args[])
{
randomTest t = new randomTest();
for (int i = 0; i < 10; i++)
System.out.println(t.generateRandomNumber());
}
}
The second class:
public class anotherClass {
private randomTest t = new randomTest();
public static void main(String args[])
{
for (int i = 0; i < 10; i++)
{
anotherClass c = new anotherClass();
System.out.println(c.t.generateRandomNumber());
}
}
}
I was trying to generate a minimal code example to track the reason why I am always getting the same random value for the whole 10 iterations. In this minimal example the results are correct and random, However In my real situation The output of the second class is the same for the whole ten iterations.
At last i was able to solve the problem by changing the method I am calling into a static method. I still don't understand how did this solve my problem, and where the original problem was.
Old Nonworking code:
...
public ImagePlus createAnImage()
{
drawBackground(c.ip);
width = ip.getWidth();
height =ip.getHeight();
createCircles(requiredCircles); // this is not creating random numbers
ArrayList<Circle> list = circlesList;
drawBoundaries(list, ip, percentage);
background.setProcessor(ip);
return background;
}
...
New Code:
...
public static ImagePlus createAnImage()
{
createCircles c = new createCircles();
c.drawBackground(c.ip);
c.width = c.ip.getWidth();
c.height =c.ip.getHeight();
c.createCircles(c.requiredCircles); // this is creating random numbers
ArrayList<Circle> list = c.circlesList;
c.drawBoundaries(list, c.ip, c.percentage);
c.background.setProcessor(c.ip);
return c.background;
}
...
In both cases I was already creating an instance of createCircles class from another class as follows:
...
private ImagePlus createRandomImage(int radius, int numberOfCircles, double minPercentage, double maxPercentage, int minBackground, int maxBackground)
{
// create the image using class createCircles
createCircles c = new createCircles();
c.setParameters(radius, radius, minBackground, maxBackground, numberOfCircles, imageWidth, imageHeight, minPercentage, maxPercentage);
ImagePlus imp = c.createAnImage(); // calling the static method works
return imp;
}
Although my problem is solved, I still need to understand the reason behind this. I suppose a better understanding of static vs. non-static methods might explain it. Anyone has a clue?
Best Regards,
M. Tleis
Do not use Math.random (it produces doubles, not integers)
use the Random class to generate random integers between 0 and N.
To generate a series of random numbers as a unit, you need to use a single Random object - do not create a new Random object for each new random number.
import java.util.Random;
/** Generate 10 random integers in the range 0..99. */
public final class RandomInteger {
public static final void main(String... aArgs){
log("Generating 10 random integers in range 0..99.");
//note a single Random object is reused here
Random randomGenerator = new Random();
for (int idx = 1; idx <= 10; ++idx){
int randomInt = randomGenerator.nextInt(100);
log("Generated : " + randomInt);
}
log("Done.");
}
private static void log(String aMessage){
System.out.println(aMessage);
}
}

Categories

Resources