Search code examples
javarandomappearancegenerated

How to check how many times one number appears in the second number?


I'm new in Java and I have a task that's going like this: Generate one number between 0-9 and a second number between 10-99. You need to check how many times the first number appears in the second number. (For example: The first number is 5 and the second one is 55 so the first number (5) apears 2 times in the second number (55) ). Btw, you need to make it without arrays.

    package randomNumber_01;
import java.util.Random;
public class third {
public static void main (String[] args){
    Random n = new Random();
    int first = n.nextInt(9)+1;
    System.out.println("First numnber: "+first);
    int second = n.nextInt(99)+10;
    System.out.println("Second number: "+second);
    System.out.println("I stuck here");
}
}

Solution

  • int count=0;
    if((second%10)==first){ 
        count++;
    }
    if(Math.round((second/10))==first){
        count++;
    }
    System.out.println(first+" occurs "+count+" times in "+second);
    

    Maybe this can help you ;), replace your last println by this 8 lines ;)

    but as shmosel sait in comment, be carreful it's

    int first = n.nextInt(10);
    
    int second = n.nextInt(90)+10;