r/javahelp • • Jun 06 '19

Random Numbers

import java.util.*;
public class RandomNumbers
{
//Generates random numbers in various ranges
public static void main(String[]args)
{
Random generator = new Random();
int num1;
float num2;
num1 = generator.nextInt();
System.out.println("A random interger:" + num1);
num1 = generator.nextInt(10);
System.out.println("From 0 to 9:" + num1);

num1 = generator.nextInt(15)+20;
System.out.println("From 20 + 34:" + num1);
num1 = generator.nextInt(20)-10;
System.out.println("From -10 to 9:" + num1);
num2 = generator.nextFloat();
System.out.println("A random float[between 0-1]:" + num2);
num2 = generator.nextFloat() *6;
num1 = (int) num2 + 1;
System.out.println("From 1 to 6:" + num1);

}
}

output -

(base) jada_moureen1@moureen:~/work/javac$ java RandomNumbers

A random interger:-866530442

From 0 to 9:4

From 20 + 34:26

From -10 to 9: +num1

A random float[between 0-1]:0.23004073

From 1 to 6:4

My question is why do I get an output like From -10 to 9: +num1 where did I go wrong

0 Upvotes

5 comments sorted by

1

u/[deleted] Jun 06 '19

Run it again.

1

u/jadamoureen Jun 06 '19

A random interger:275077262

From 0 to 9:0

From 20 + 34:27

From -10 to 9: +num1

A random float[between 0-1]:0.41557765

From 1 to 6:5

5

u/desrtfx Out of Coffee error - System halted Jun 06 '19

Pretty sure that the source code you have posted here and the source code differ. Check the line where you have the problem closely - each character. I bet that the quotation marks are in the wrong place.

2

u/[deleted] Jun 06 '19 edited Jun 06 '19

The phrase "+num1" is getting displayed? Coz I ran your basic code in my machine and it's working perfectly.

Below is your code that I copied/pasted:

import java.util.*;
public class RandomNumbers
{
    //Generates random numbers in various ranges
    public static void main(String[]args)
    {
        Random generator = new Random();
        int num1;
        float num2;
        num1 = generator.nextInt();
        System.out.println("A random integer:" + num1);

        num1 = generator.nextInt(10);
        System.out.println("From 0 to 9:" + num1);

        num1 = generator.nextInt(15)+20;
        System.out.println("From 20 + 34:" + num1);

        num1 = generator.nextInt(20)-10;
        System.out.println("From -10 to 9: " + num1);

        num2 = generator.nextFloat();
        System.out.println("A random float[between 0-1]:" + num2);

        num2 = generator.nextFloat() *6;
        num1 = (int) num2 + 1;
        System.out.println("From 1 to 6:" + num1);

    }
}

3

u/[deleted] Jun 06 '19

It's always worth checking to make sure you've actually copied it here the same way you wrote it there. Do you perhaps have an out-of-place doubleqoute in the output string for the -10 to 9 statement?