Search code examples
javaloopswhile-loopnestednested-loops

How to get values you type inside a loop?


Can you see the last println? the System.out.println (iInputSlot1P1);

Why can I not get the value of iInputSlot1P1 thats inside the loop, it said that it is not initialised. Help me please, Im a beginner.

import javax.swing.* ;
import java.util.* ;

public class assfinal {

    public static void main(String[] args) {

        int  playerslots[] = new int [10] ;
        int cardslots[] = new int [10] ;
        String sInputSlot1P1, sInputSlot3P1, sInputSlot5P1, sInputSlot7P1, sInputSlot9P1, sInputSlot2P2, sInputSlot4P2, sInputSlot6P2, sInputSlot8P2, sInputCard1P1, sInputCard3P1, sInputCard5P1, sInputCard7P1, sInputCard9P1, sInputCard2P2, sInputCard4P2, sInputCard6P2, sInputCard8P2 ;
        int iInputSlot1P1, iInputSlot3P1, iInputSlot5P1, iInputSlot7P1, iInputSlot9P1, iInputSlot2P2, iInputSlot4P2, iInputSlot6P2, iInputSlot8P2, iInputCard1P1, iInputCard3P1, iInputCard5P1, iInputCard7P1, iInputCard9P1, iInputCard2P2, iInputCard4P2, iInputCard6P2, iInputCard8P2 ;
        int counter = 0 ; int innercounter = 0 ; int counter1 = 0 ; int innercounter1 = 0 ;
        int trybreak1 ; int trybreak2 ;

        //Player 1 Input Slot number
        while (counter == 0) {
            trybreak1: while (innercounter == 0) {
                sInputSlot1P1 = JOptionPane.showInputDialog ("Player 1\nEnter Slot Number:") ;

                if (sInputSlot1P1 == null) 
                    System.exit(0) ;
                else if (sInputSlot1P1.equalsIgnoreCase(""))
                    JOptionPane.showMessageDialog(null,"Enter a number.","WARNING!",JOptionPane.WARNING_MESSAGE) ;
                else {
                    try {
                        iInputSlot1P1 = Integer.parseInt(sInputSlot1P1) ;

                        if ((iInputSlot1P1 < 1) || (iInputSlot1P1 > 9)){
                            JOptionPane.showMessageDialog(null,"Slot Number is only 1 - 9.","WARNING!",JOptionPane.WARNING_MESSAGE) ;
                            break trybreak1;
                        }
                        else {
                            counter++ ;
                            innercounter++ ;

                            playerslots[iInputSlot1P1] = 1;
                        }
                    }
                    catch (NumberFormatException cfe1) {
                        JOptionPane.showMessageDialog(null,"Enter a number only from 1 - 9 (Specifically, Decimal numbers are not accepted.).","WARNING!",JOptionPane.WARNING_MESSAGE) ;
                    }
                }
            }
        }
        System.out.println (iInputSlot1P1) ;
    }
}

Solution

  • It is a compiler error. Java complier assumes that the loop might not be executed at all keeping the variable uninitialized. So it flags the statement with uninitialized error.

    Just add String sInputSlot1P1=null; Before the loop