I am a student. I have a problem with my homework this week.
package week2_class_work;
import javax.swing.*;
/**
* The Dice game of enter 1~6 with computer.
* @version 2020-03-27
*/
public class DiceGame
{
public static void main(String[] args)
{
double random_num = Math.random();
String str;
do
{
String numberstr = JOptionPane.showInputDialog("Please enter a number of 1~6: ");
int number = Integer.parseInt(numberstr);
if (number < 1 || number > 6)
{
System.out.println("Input error! Please enter again!");
continue;
}
int random_num_int = (int) (random_num * 6 + 1);
if (number > random_num_int)
System.out.println("You win!");
if (number == random_num_int)
System.out.println("Play even!");
if (number < random_num_int)
System.out.println("You lose!");
str = JOptionPane.showInputDialog("Once again? (Yes/No): ");
}
while (str.equals("Yes"));
}
}
This is my code. The str
may not have been initialized. When I changed it to...
String str = null;
it worked. I want know why I should do this? also when I deleted
if (number < 1 || number > 6)
{
System.out.println("Input error! Please enter again!");
continue;
}
This code is worked even if str is not initialized. I want know this is why?