gpt4 book ai didi

java - 用户输入try&catch

转载 作者:行者123 更新时间:2023-12-02 12:05:01 25 4
gpt4 key购买 nike

我正在尝试异常(exception),因此当用户输入数字而不是字符时,会弹出一条错误消息,尝试编写 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) {

}
}

谢谢。

最佳答案

您可以使用 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;
}

关于java - 用户输入try&catch,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46954324/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com