-1

I need to get a random value between 0 and 100 in String format.

I use Random class, but when i cast the result in String, the non significative 0 are not kepped.

 sb.append((rand.nextInt(99)));

Is there a method in StringBuilder or Random for force the result with this 0 ?

Broshet
  • 133
  • 12
  • 2
    What would you expect `Random` to do here? It just returns an `int`, and there's no notion of an `int` having a difference between 1, 01, or 001. I suspect you want to format the integer as a string first, then append that string to the `StringBuilder`. So the next thing to research is "formatting integers as strings in Java". – Jon Skeet Feb 03 '21 at 08:13
  • I need to generate a French phone number with 0X YY YY YY YY format. X is between 0 and 7, NN are number between 0 and 99 with significative 0. But with this command, StringBuilder don't add these 0 ... – Broshet Feb 03 '21 at 08:15
  • No sorry, my previous post was incomplter. See above – Broshet Feb 03 '21 at 08:18
  • @Broshet I don't really see how that invalidates the answers in the link I mentioned. `sb.append(String.format("%02d", rand.nextInt(99)));` always appends two digits. When the random number is less than 10, it will prepend a `0`. – Ivar Feb 03 '21 at 08:24
  • *FYI:* `nextInt(99)` generates a number in range 0-98 *(both inclusive)*, not a number "between 0 and 100", where it is unspecified whether 0 and 100 are considered "between" too. If yes, range would be 0-100, if no range would be 1-99. None of this generates a number in range 0-99, which is what I think you're looking for. – Andreas Feb 03 '21 at 08:45
  • That's it: I want get the numbers between 0 and 99 inclusive, i will use range 0-100. Thanks – Broshet Feb 03 '21 at 12:40

2 Answers2

3

You asked: Is there a method in StringBuilder or Random for force the result with this 0 ?

Answer: No. You need to research for String formatting options. One options is String.format().

Example:

String formatted = String.format("%03d", rand.nextInt(99));
sb.append( formatted );
0

You can use String.format:

public class FormatExample {  
    public static void main(String[] args) {         
        int i = 4;
        int j = 44;
        int k = 102;
        String str1 = String.format("%03d", i);  
        String str2 = String.format("%03d", j);  
        String str3 = String.format("%03d", k); 

        System.out.println(str1);  
        System.out.println(str2);  
        System.out.println(str3);  
    }  
}

Prints:

004
044
102
don-joe
  • 600
  • 1
  • 4
  • 12
  • Thanks, I misunderstood the syntax. This is what I was looking for. Thank you all for your help. My explanation was ambiguous, it was 2 digits (00 to 99) – Broshet Feb 03 '21 at 08:35