How to select random two consecutive digits from a number in Java

1 Answer

0 votes
import java.util.Random;

public class RandomTwoDigits {

    // Function to select random two consecutive digits from a number
    public static String getRandomTwoDigits(int num) {
        String s = Integer.toString(num);

        if (s.length() < 2) {
            return "Error: number must have at least 2 digits";
        }

        Random rand = new Random();
        int start = rand.nextInt(s.length() - 1); // random index

        return s.substring(start, start + 2);
    }

    public static void main(String[] args) {
        int num = 123456;
        String randomTwo = getRandomTwoDigits(num);

        System.out.println("Random two digits: " + randomTwo);
    }
}


     
/*
run:
    
Random two digits: 23
  
*/


 

 



answered Nov 25, 2025 by avibootz
...