0

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?

  • https://stackoverflow.com/questions/2448843/variable-might-not-have-been-initialized-error – Donald Wu Mar 27 '20 at 05:39
  • Because it is a Local Variables [Why must local variables, including primitives, always be initialized in Java?](https://stackoverflow.com/questions/1560685/why-must-local-variables-including-primitives-always-be-initialized-in-java) – Melchizedek Mar 27 '20 at 05:41
  • `String str = null;` I would set to a non-null value. If by chance, the `str` did not get set within your `do^while`, then if it was `null`, you would get a NPE at `while (str.equals("Yes"));` – Scary Wombat Mar 27 '20 at 05:42
  • But when I deleted```if (number < 1 || number > 6) { System.out.println("Input error! Please enter again!"); continue; }``` is worked. why? – Tourscholar Mar 27 '20 at 06:13

0 Answers0