简体   繁体   中英

Java exception handling with multiple classes

I need to make the following exceptions: NoSuchRowException if the row is not between 1 and 3, IllegalSticksException if the number of sticks taken is not between 1 and 3, and NotEnoughSticksException if the number of sticks taken is between 1 and 3, but more than the number of sticks remaining in that row. My issue is I really don't understand the syntax. If someone could help me get started with one exception, I think I can figure the others out.

So far I have the main class:

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

The support class:

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

}

My issue is I really don't understand the syntax.

There is nothing wrong with the syntax as you have written it.

The problem is that you are catching the exception at the wrong place. You are (apparently) intending play to propagate the IllegalSticksException to its caller. But that won't happen because you are catching it within the play method.

There are two possible fixes depending on what you actually intent to happen .

  • You could remove the throws IllegalSticksException from the play signature.

  • You could remove the catch (IllegalSticksException ex){ ... } in play and catch/handle the exception at an outer level.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM