java try / catch问题我想在字符串选项中输入整数

时间:2017-05-13 01:43:52

标签: java

有点坚持这个问题,但我怎么能让我尝试捕获只允许字符串进入输入框。 (相关的代码是在底部,对于凌乱的格式仍然很新的图形编程抱歉)我认为我的代码将工作,但我想它没有,我现在还不太确定它是否可以抓住它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 个答案:

答案 0 :(得分:0)

您可以做的一件事是创建一个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;
}

答案 1 :(得分:0)

我从您的代码中获得的是:您希望确保用户在特定字段中输入正确的值,验证类型。如果您想确保用户为每个字段输入正确的值,那么使用单个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;
    }                
}