Activity 1.22.1.
Write the code to print a random number from 1 to 100. You can use
Math.random()
to get a value between 0 and not quite 1.
Solution.
First multiply the output from Math.random() times 100 and then cast it to an integer. This will result in a random number from 0 to 99. Add one to make it from 1 to 100.
public class Test1
{
public static void main(String[] args)
{
System.out.println(((int) (Math.random() * 100)) + 1);
}
}