Reputation: 1
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.
Upvotes: 0
Views: 35
Reputation: 13914
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;
}
Upvotes: 1