簡體   English   中英

多個類的 Java 異常處理

[英]Java exception handling with multiple classes

我需要做以下例外:NoSuchRowException 如果行不在 1 和 3 之間,IllegalSticksException 如果取的棒數不在 1 到 3 之間,如果取的棒數在 1 到 3 之間,但大於 NotEnoughSticksException該行剩余的木棍數量。 我的問題是我真的不明白語法。 如果有人可以幫助我從一個例外開始,我想我可以弄清楚其他的。

到目前為止,我有主要課程:

 /*
 * 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();
    }
}

}

我的問題是我真的不明白語法。

您編寫的語法沒有任何問題。

問題是你在錯誤的地方捕捉到異常。 你是(顯然)打算play到傳播IllegalSticksException到其調用者。 但這不會發生,因為您是play方法中捕獲它的。

根據您的實際意圖,有兩種可能的修復方法。

  • 您可以從play簽名中刪除throws IllegalSticksException

  • 您可以在play刪除catch (IllegalSticksException ex){ ... }並在外部級別捕獲/處理異常。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM