我正在尝试进行异常,因此当用户输入数字而不是字符时会弹出错误消息,尝试编写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;
我想要打印''请输入一个字符''而不是''数字'。我该如何填写正确的方法?
public String userInputToVariable() {
try {
input = welcomeScreen.playerNameWindows();
return input;
}
catch (Exception e) {
}
}
谢谢。
答案 0 :(得分:1)
您可以使用Java已经拥有的java.lang.Character类专用于此目的的方法。如果字符是数字,则返回true。
Character.isDigit(string.charAt(index))
如果您有兴趣,其实施如下:
public static boolean isDigit(char ch) {
return isDigit((int)ch);
}
public static boolean isDigit(int codePoint) {
return getType(codePoint) == Character.DECIMAL_DIGIT_NUMBER;
}