有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java try/catch问题我想捕获在字符串选项中输入的int

有点被这个问题困住了,但是我如何让我的try-catch只允许字符串进入输入框呢。(这里的相关代码位于底部,很抱歉,对于图形编程来说,混乱的格式仍然是非常新的)我认为下面的代码可以工作,但是我想它不行,我现在不太确定是否能够捕获sting输入中的所有int,因为那里的int是作为字符串输入的。此外,如果您可以查看电子邮件try/catch,也可以在出现@标志时弹出错误框,因为它有点类似。谢谢

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.util.ArrayList;
import java.util.InputMismatchException;

import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.Timer;


public class MainPanel extends JPanel {

    Player myPlayer;
    Player myOtherPlayer;
    private int WIDTH = 1000;
    private int HEIGHT = 1000;
    private int WALLWIDTH = 100;
    private int WALLHEIGHT = 100;
    private ArrayList<Wall> walls = new ArrayList<Wall>();
    String Name;
    String Email;
    int favNum;

    Timer myTimer = new Timer(500, new timerListener());    
    JLabel myTimeLabel;
    int time =1;



    public MainPanel()
    {
        setPreferredSize(new Dimension(WIDTH,HEIGHT));
        JLabel myLabel= new JLabel ("Game ends once 30 seconds is receahed:");
        myLabel.setFont(new Font("Serif", Font.BOLD,32));
        myLabel.setForeground(Color.WHITE);
        myTimeLabel= new JLabel (Integer.toString(time));
        myTimeLabel.setFont(new Font("Serif", Font.BOLD,32));
        myTimer.start();

        add(myLabel);
        add(myTimeLabel);
        myPlayer = new Player(0,100, "toad.png", KeyEvent.VK_UP, KeyEvent.VK_DOWN, KeyEvent.VK_LEFT, KeyEvent.VK_RIGHT,this, 50, 38);
        myOtherPlayer = new Player(200,200, "toad.png", KeyEvent.VK_W, KeyEvent.VK_S, KeyEvent.VK_A, KeyEvent.VK_D,this, 50, 38);
        createWalls();




    }

    public ArrayList<Wall> getWalls() {
        return walls;
    }

    public void createWalls()
    {
        int j = 0;
        for(int i = 0; i < HEIGHT/WALLHEIGHT; i++)
        {
            for(int k = 0; k < WIDTH/WALLWIDTH; k++)
            {
                if(i == 0 || i == (HEIGHT/WALLHEIGHT-1))
                {
                    walls.add(new Wall(k*WALLWIDTH,j,"road.png", 100, 100));
                }

            }
            j+=WALLHEIGHT;
        }
    }


    private class timerListener implements ActionListener
    {


        public void actionPerformed(ActionEvent e) {
            time++;
            myTimeLabel.setText(Integer.toString(time));
            myTimeLabel.setForeground(Color.WHITE);
            if(time == 31)
            {
                myTimer.stop();
            }
            repaint();
        }

    }


    public void paintComponent(Graphics page)
    {
        super.paintComponent(page);

        page.drawImage(myPlayer.getImageIcon().getImage(), myPlayer.getX(), myPlayer.getY(), null);
        page.drawImage(myOtherPlayer.getImageIcon().getImage(), myOtherPlayer.getX(), myOtherPlayer.getY(), null);


        for(int i = 0; i < walls.size(); i++)
        {
            page.drawImage(walls.get(i).getImageIcon().getImage(), walls.get(i).getX(), walls.get(i).getY(), null);


        }

        page.setFont(new Font("Arial", Font.PLAIN,32)); 
        page.drawString("Player 1 Score: " + myPlayer.getScore(), 100, 800);
        page.drawString("Player 2 Score: " + myOtherPlayer.getScore(), 100, 850);
        myPlayer.checkOffScreen();

        if(time == 5)
        {
            page.drawString("GAME OVER", WIDTH/2-100, HEIGHT/2);



            try{
                Name = JOptionPane.showInputDialog("What is your name?");
                }catch (NumberFormatException  e) {
                    if (!Name.matches("^[a-z][a-z ]*[a-z]?$")){
                    JOptionPane.showInputDialog("You entered a number, this only accepts alphabetical letters. Please enter your name");}
                }

            try{
                favNum= Integer.parseInt(JOptionPane.showInputDialog("What is your favorite number?")); 
                }catch (NumberFormatException  e) {

                JOptionPane.showInputDialog("You entered a text, this only accepts numbers . Please enter your  favorite number");}

            try{
                Email =JOptionPane.showInputDialog("Please enter your email");
                }catch (InputMismatchException  e) {
                JOptionPane.showInputDialog("You enter your email incorrectly. Please include an @ sign with it");}
                }

            }

    }

共 (2) 个答案

  1. # 1 楼答案

    我从你的代码中得到的是:你想确保用户在特定字段中输入正确的值,这是一种验证。如果您想确保用户为每个字段输入正确的值,那么使用单个try-catch块将很难处理它。您可以尝试下面的逻辑,它将不允许用户进一步移动,直到他为特定字段输入正确的输入。我已经为Name字段做了这项工作,类似地,您也可以为其他字段做这项工作:

    boolean error=true;                        
    Name = JOptionPane.showInputDialog("What is your name?");                
    if (!Name.matches("^[a-zA-Z ]*$")){
        error=true;
    }        
    while(error){                                
        Name = JOptionPane.showInputDialog("You entered a number, this only accepts alphabetical letters. Please enter your name");
        if (Name.matches("^[a-zA-Z ]*$")){
             error=false;
        }                
    }
    
  2. # 2 楼答案

    你可以做的一件事是创建一个isInteger方法

    protected static boolean isInteger(String s) {
        try {
            Integer.parseInt(s);
        } catch(NumberFormatException e) {
            return false;
        } catch(NullPointerException e) {
            return false;
        }
        // String can be changed into an integer
        return true;
    }