228k views
2 votes
Please help with coding assignment.

Java

Write a method where you have to generate random numbers between 1 to 9 until you get the number 5, and you do it j number of times. (j represents how many times you can generate.) If you do get to 5 under j number of times, you skip a line and end the method. Write the method stopAtFive.


public int stopAtFive (int j)

1 Answer

1 vote

Answer:

import java.util.Random;

class Main {

public int stopAtFive (int j) {

Random rand = new Random();

int number = 0;

for(int i=0; i<j; i++) {

number = rand.nextInt(9)+1;

System.out.println(number);

if (number == 5) {

System.out.println();

break;

}

}

return number;

}

public static void main(String args[]) {

Main main = new Main();

main.stopAtFive(20);

main.stopAtFive(20);

}

}

Step-by-step explanation:

Your requirements do not say what has to be displayed or returned from the method, but you can use this as a starting point.

User Duddel
by
5.5k points