2014-03-20 2 views
0

저는 프로그래밍에 익숙하지 않아 숙제를 완전히 잃었습니다. 과제는 두 개의 다른 주사위를 표시하는 gui를 갖는 것입니다. 버튼을 클릭하면 난수 생성기에 주사위의 다른 이미지가 표시됩니다. "if"문이 없을 때 이미지가 나타나서 경로가 작동 중임을 알 수 있습니다. 주사위 중 하나의 이미지를 지정하기 위해 "if"문을 추가 할 때 기호를 찾을 수 없다는 오류가 발생합니다. 아이콘이 정적으로 할당되었을 때 작동했기 때문에 문제가 발생한 "if"문이라고 가정하지만 임의의 숫자로 돌아올 수 있습니다. 내가 뭘 잘못하고 있는지 조언 해주세요. 부착 된 코드는 왼쪽 다이에 대해 작동하지 않는 코드 만 가지고 있습니다. 당신은 범위 문제에 직면하고있다난수 생성기를 기반으로 한 GUI에 다른 이미지가 나타나기 시작합니다.

private class ButtonListener implements ActionListener 
{ 
    public void actionPerformed(ActionEvent e) 
    { 

     Random randomNumbers = new Random(); // Generates random numbers 
     int valLeft; // holds random number 
     int valRight; // holds random number 

     // get values for the dice 
     valLeft = randomNumbers.nextInt(6)+1; // range 1-6 
     valRight = randomNumbers.nextInt(6)+1; // range 1-6 

     // assign the image for the left die 
     if (valLeft==1) 
     { 
      ImageIcon leftDie = new ImageIcon("Die1.png"); 
     } 
     if (valLeft==2) 
     { 
      ImageIcon leftDie = new ImageIcon("Die2.png"); 
     } 
      if (valLeft==3) 
     { 
      ImageIcon leftDie = new ImageIcon("Die3.png"); 
     } 
      if (valLeft==4) 
     { 
      ImageIcon leftDie = new ImageIcon("Die4.png"); 
     } 
      if (valLeft==5) 
     { 
      ImageIcon leftDie = new ImageIcon("Die5.png"); 
     } 
      if (valLeft==6) 
     { 
      ImageIcon leftDie = new ImageIcon("Die6.png"); 
     } 


     // put image on label 
     imageLabelLeft.setIcon(leftDie); 

     // assign the image for the right die 
     ImageIcon rightDie = new ImageIcon("Die6.png"); 
     imageLabelRight.setIcon(rightDie); 

     // remove the text from the labels 
     imageLabelLeft.setText(null); 
     imageLabelRight.setText(null); 

     // repack the frame for the new images 
     pack(); 

    } 
} 

답변

3

leftDie 범위는 블록 만 그래서, 당신의 if 문 밖으로 ImageIcon leftDie ==를 이동하는 경우로 제한됩니다. 이 코드를 변경합니다

if (valLeft==1) 
    { 
     ImageIcon leftDie = new ImageIcon("Die1.png"); 
    } 

이 좋아하려면

ImageIcon leftDie = null; 
    if (valLeft==1) 
    { 
     leftDie = new ImageIcon("Die1.png"); 
    } 

이 작동합니다.

관련 문제