简体   繁体   中英

User input try&catch

I'm trying making a exception so when a user inputs a number instead of a character there will pop up a error message, trying to write try/catch,

package Controller;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.InputMismatchException;
import java.util.Scanner;

import javax.swing.JButton;

import Model.BoardSpace;
import Model.PlayerMarker;
import Model.PlayerObject;
import View.MainFrame;
import View.WelcomeScreen;
import View.WinScreen;

public class GameInit implements Game {

    private WelcomeScreen welcomeScreen = new WelcomeScreen();

      public GameInit() {

      }

      public void gameInit() {
      initPlayers();

      welcomeScreen.inputBoardSize();
      setButtons(welcomeScreen.getButtons());
      boardSizeListeners();

      }


private PlayerObject playerOne, playerTwo, victorPlayer;
private String input;
private int players = 1;
private boolean gameRunning = true;
WinScreen win = new WinScreen();

private static GameMechanics mechanics = GameMechanics.getInstance();
private MainFrame mainFrame = new MainFrame();
private int row, col;
private JButton buttons[];
// used on size selection
private int boardSizeOption;

i wanna it to print ''Please enter a character'' instead of a ''number'. how can i fill in correct way?

public String userInputToVariable() {

try {
    input = welcomeScreen.playerNameWindows();
    return input;
    }
catch (Exception e) {

    }
}

Thank you.

You can use the method especially dedicated to this purpose that Java already has from java.lang.Character class. Returns true if the character is a digit.

Character.isDigit(string.charAt(index))

If you are interested, its implementation is as follows:

public static boolean isDigit(char ch) {
    return isDigit((int)ch);
}

public static boolean isDigit(int codePoint) {
    return getType(codePoint) == Character.DECIMAL_DIGIT_NUMBER;
}

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