-3

I am writing some code that gives me a random string of numbers, they need to list under on integer but each number needs to be under a different math.random. For Instance, if two separate number are listed like 5 and 7, I don't want it to print 12, I would like it to print 57. But i don't want to use the System.out.println(Number1+Number2); way.

I have tried using the "&" Sign multiple ways but none seem to work.

   int Number1 = 1 + (int)(Math.random() * ((5) + 1));
   int Number2 = 1 + (int)(Math.random() * ((5) + 1));
   int Number3 = 1 + (int)(Math.random() * ((5) + 1));

   int finalcode=Number1&Number2&Number3;


    System.out.println("Promo Code Genorator:");
    System.out.println(" ");
    System.out.println("Your Promo Code Is: "+finalcode);

Instead, what happens is it picks the lowest number from there and prints them. Any Ideas?

2 Answers2

1

It is suggested to use String if you want to combine a variety of numbers together.

You can write it like this:

int Number1 = 1 + (int)(Math.random() * ((5) + 1));
int Number2 = 1 + (int)(Math.random() * ((5) + 1));
int Number3 = 1 + (int)(Math.random() * ((5) + 1));

String finalcode = String.valueOf(Number1) + String.valueOf(Number2) + String.valueOf(Number3);

System.out.println("Promo Code Genorator:");
System.out.println(" ");
System.out.println("Your Promo Code Is: "+finalcode);

If you really need your final code to be a integer, you can use

int finalcode = Integer.parseInt(String.valueOf(Number1) + String.valueOf(Number2) + String.valueOf(Number3));

in which Integer.parseInt(String string) takes in a string and return a integer.

FYI, if you want to convert it to long instead of integer, use Long.parseLong(String string).

Hope this helps!

GBlodgett
  • 12,704
  • 4
  • 31
  • 45
0

This seems like a nice problem to solve using streams and functional programming.

import java.util.stream.Stream;
import java.util.stream.Collectors;

public class LazyNumbersTest {

    public static void main(String[] args) {

        int result = Integer.parseInt(
            Stream.generate(() -> (int)(Math.random() * ((5) + 1)))
                  .peek(System.out::println)
                  .limit(3)
                  .map(Object::toString)
                  .collect(Collectors.joining(""))
        );

        System.out.println("Promo Code Generator:");
        System.out.println(" ");
        System.out.println("Your Promo Code Is: " + result);        
    }
}

It's an infinite stream of random numbers, from which we pluck the first 3 and convert them to string, then join them together and convert to an integer.

If you want more or less numbers in the calculation, just change the number in limit. It's a shame I couldn't include the parseInt in the stream of fluent operations (without making it really ugly).

Paul Rooney
  • 20,879
  • 9
  • 40
  • 61