如果/ for循环问题

时间:2013-12-01 22:20:21

标签: java loops if-statement for-loop

我正在制造战舰的一个变种,而我正试图让它成为每个按钮,当被按下时,如果是击中则变为绿色,如果是未命中则变为红色。船舶的坐标从导入的文本文件的随机行中读取,并在主程序启动时存储到数字[]中。我可以让按钮用于数组的第一个整数,但for循环似乎没有完成。这是代码:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.Scanner;
import java.io.*;
import java.util.Random;
import java.util.*;

public class Buttons extends JPanel 
{
 JButton[] btn; 
 static int[] numbers = new int[5];

  public Buttons() throws IOException
 {
String[] numberLine = choose(new File("Coords.txt")).split(",");

    for(int i = 0; i < 5; i++)
    {
numbers[i] = Integer.parseInt(numberLine[i]);
        }

String letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
btn = new JButton[25];

setLayout(new GridLayout(5,5));

setBackground(Color.blue);
setPreferredSize(new Dimension(300,300));

for(int i=0;i<25;i++)
    btn[i] = new JButton(letters.charAt(i) + Integer.toString(i));



ButtonListener blisten = new ButtonListener();

  for(int i=0;i<25;i++)
  {
  btn[i].addActionListener(blisten);

  }



  for(int i=0;i<25;i++)
  {
  add (btn[i]);
  }


} //Ends Constructor

    private class ButtonListener implements ActionListener
 {


public void actionPerformed (ActionEvent event)
{
  Object source = event.getSource();

  for(int i=0;i<25;i++)
   for(int u=0;u<5;u++) //This is where the issue seems to be.
    if(source==btn[i])  //It only does the for loop for u=0 (I think).
      if(i==numbers[u]) //Because only one button comes out as a hit.
  {
    btn[i].setBackground(Color.green);
    btn[i].setEnabled(false);
    }
    else
    {
    btn[i].setBackground(Color.red);
    btn[i].setEnabled(false);

    }



    }
}



public static String choose(File f) throws FileNotFoundException
{
 String result = null;
 Random rand = new Random();
 int n = 0;
 for(Scanner sc = new Scanner(f); sc.hasNext(); )
 {
    ++n;
    String line = sc.nextLine();
    if(rand.nextInt(n) == 0)
       result = line;         
 }

 return result;      
}

} //Ends Program

任何帮助都将不胜感激。

0 个答案:

没有答案