具有多个类的Java异常处理

时间:2016-04-02 02:41:29

标签: java oop exception-handling

我需要做出以下例外:NoSuchRowException如果行不在1和3之间,IllegalSticksException如果棍子的数量不在1和3之间,NotEnoughSticksException如果棍子的数量在1和3之间,但超过该行剩余的棒数。我的问题是我真的不懂语法。 如果有人可以帮助我开始使用一个例外,我想我可以解决其他问题。

到目前为止,我有主要课程:

 /*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package nimapp;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

/**
 *
 * @author jrsullins
 */
public class NimApp extends JFrame implements ActionListener {
    private static final int ROWS = 3;
    private JTextField[] gameFields; // Where sticks for each row shown
    private JTextField rowField;     // Where player enters row to select
    private JTextField sticksField;  // Where player enters sticks to take
    private JButton playButton;      // Pressed to take sticks
    private JButton AIButton;        // Pressed to make AI's move
    private NimGame nim;

    public NimApp() {
        // Build the fields for the game play 
        rowField = new JTextField(5);
        sticksField = new JTextField(5);
        playButton = new JButton("PLAYER");
        AIButton = new JButton("COMPUTER");
        playButton.addActionListener(this);
        AIButton.addActionListener(this);
        AIButton.setEnabled(false);

        // Create the layout
        JPanel mainPanel = new JPanel(new BorderLayout());
        getContentPane().add(mainPanel);

        JPanel sticksPanel = new JPanel(new GridLayout(3, 1));
        mainPanel.add(sticksPanel, BorderLayout.EAST);

        JPanel playPanel = new JPanel(new GridLayout(3, 2));
        mainPanel.add(playPanel, BorderLayout.CENTER);

        // Add the fields to the play panel
        playPanel.add(new JLabel("Row: ", JLabel.RIGHT));
        playPanel.add(rowField);
        playPanel.add(new JLabel("Sticks: ", JLabel.RIGHT));
        playPanel.add(sticksField);
        playPanel.add(playButton);
        playPanel.add(AIButton);

        // Build the array of textfields to display the sticks
        gameFields = new JTextField[ROWS];
        for (int i = 0; i < ROWS; i++) {
            gameFields[i] = new JTextField(10);
            gameFields[i].setEditable(false);
            sticksPanel.add(gameFields[i]);
        }
        setSize(350, 150);
        setVisible(true);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        nim = new NimGame(new int[]{3, 5, 7});
        draw();
    }

    // Utility function to redraw game
    private void draw() {
        for (int row = 0; row < ROWS; row++) {
            String sticks = "";
            for (int j = 0; j < nim.getRow(row); j++) {
                sticks += "|   ";
            }
            gameFields[row].setText(sticks);
        }
        rowField.setText("");
        sticksField.setText("");
    }

    public void actionPerformed(ActionEvent e) {
        // Player move
        if (e.getSource() == playButton) {
            // Get the row and number of sticks to take
            int row = Integer.parseInt(rowField.getText())-1;
            int sticks = Integer.parseInt(sticksField.getText());

            // Play that move
            nim.play(row, sticks);

            // Redisplay the board and enable the AI button
            draw();
            playButton.setEnabled(false);
            AIButton.setEnabled(true);

            // Determine whether the game is over
            if (nim.isOver()) {
                JOptionPane.showMessageDialog(null, "You win!");
                playButton.setEnabled(false);
            }
        }

        // Computer move
        if (e.getSource() == AIButton) {
            // Determine computer move
            nim.AIMove();
            // Redraw board
            draw();
            AIButton.setEnabled(false);
            playButton.setEnabled(true);

            // Is the game over?
            if (nim.isOver()) {
                JOptionPane.showMessageDialog(null, "You win!");
                playButton.setEnabled(false);
            }
        }
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        NimApp a = new NimApp();
    }
}

支持类:

package nimapp;
import java.util.Random;
import javax.swing.JOptionPane;
import java.io.*;
import java.lang.*;

public class NimGame { 
    int x = 1;
    int[] Sticks; //creating an array of sticks
    int totalSticks = 0;

    public NimGame(int[] initialSticks){
    Sticks = initialSticks;}

    public int getRow(int r){
        return Sticks[r];}

    public void play(int r, int s) throws IllegalSticksException {
        try {
            Sticks[r]=Sticks[r]-s;               
            if(s < 0 || s > 3)
                throw new IllegalSticksException();
        } catch (IllegalSticksException ex){
             JOptionPane.showMessageDialog(null, "Not a valid row!");
        } catch (IndexOutOfBoundsException e){
             JOptionPane.showMessageDialog(null, "Too Many Sticks!");
        }
    }





public boolean isOver(){
    int theTotal = 0;
    for (int i = 0; i< Sticks.length; i++){
         theTotal = Sticks[i];
    System.out.println(Sticks[i]);
    System.out.println(theTotal);
    }
       totalSticks = theTotal; 
       if (totalSticks <= 0){            
           return true;
        }
        else return false;
}

public void AIMove(){
    Random randomInt = new Random ();

    boolean tryRemove =  true;

    while(tryRemove && totalSticks >= 1){
        int RandomRow = randomInt.nextInt(3);
        if(Sticks[RandomRow] <= 0)//the computer can't remove from this row
            continue;

        //the max number to remove from row
        int size = 3;
        if( Sticks[RandomRow] < 3)//this row have least that 3 cards
            size = Sticks[RandomRow];//make the max number to remove from the row be the number of cards on the row 
        int RandomDiscard = randomInt.nextInt(size) + 1;
        Sticks[RandomRow] = Sticks[RandomRow] - RandomDiscard;
        //I don't know if this is needed, but since we remove a RandomDiscard amount lest decrease the totalSticks
        totalSticks = totalSticks - RandomDiscard;
        //exit loop
        tryRemove = false;
    }

     if(totalSticks <= 1){
        int RandomRow = 0;
        Sticks[RandomRow] = Sticks[RandomRow]-1;
        isOver();
    }
}

}

1 个答案:

答案 0 :(得分:0)

  

我的问题是我真的不懂语法。

您编写语法时没有任何问题。

问题是您在错误的地方捕获异常。您(显然)打算playIllegalSticksException传播给其来电者。但这不会发生,因为你正在 play方法中捕获它。

有两种可能的修复取决于您实际意图发生的事情

  • 您可以从throws IllegalSticksException签名中删除play

  • 您可以删除catch (IllegalSticksException ex){ ... }中的play并在外层捕获/处理异常。