Java Char空字符检测
Java Char Empty Character Detection
是的,所以我在 eclipse 上使用 java 并不断遇到问题。我试图修复的是当用户被提升为按任意键时。当输入键但没有字符时,程序会因为找不到字符而崩溃。
我的代码是:
Scanner scan = new Scanner(System.in);
Game game = new Game();
char quit=' ';
while (quit != 'N')
{
game.play();
System.out.println("Play again? Press any key to continue, or 'N' to quit");
quit = scan.nextLine().toUpperCase().charAt(0);
}
当按下回车键时,由于没有输入字符,它会停止程序。有没有办法解决这个问题并让程序在按下回车键时继续?
您可以查看长度:
while (quit != 'N')
{
game.play();
System.out.println("Play again? Press any key to continue, or 'N' to quit");
String test = scan.nextLine().toUpperCase();
if(test != null && test.length() > 0)
{
quit = test.toUpperCase().charAt(0);
}
else
{
//handle your else here
quit = ' '; //this will keep it from terminating
}
}
将下一行存储在字符串中,然后检查以确保它不为空且长度至少为 1。如果是,则获取第一个字符。如果没有,那么决定你想如何处理这种情况。
我会这样写:
Scanner scan = new Scanner(System.in);
String line;
do{
game.play();
System.out.println("Play again? Press any key to continue, or 'N' to quit");
line = scan.nextLine();
}while (line.isEmpty() || line.toUpperCase().charAt(0) != 'N');
代替quit = scan.nextLine().toUpperCase().charAt(0);
,我们可以这样写:
String str = scan.nextLine().toUpperCase();
quit = ((str == null || "".equals(str)) ? ' ' : str.charAt(0));
是的,所以我在 eclipse 上使用 java 并不断遇到问题。我试图修复的是当用户被提升为按任意键时。当输入键但没有字符时,程序会因为找不到字符而崩溃。
我的代码是:
Scanner scan = new Scanner(System.in);
Game game = new Game();
char quit=' ';
while (quit != 'N')
{
game.play();
System.out.println("Play again? Press any key to continue, or 'N' to quit");
quit = scan.nextLine().toUpperCase().charAt(0);
}
当按下回车键时,由于没有输入字符,它会停止程序。有没有办法解决这个问题并让程序在按下回车键时继续?
您可以查看长度:
while (quit != 'N')
{
game.play();
System.out.println("Play again? Press any key to continue, or 'N' to quit");
String test = scan.nextLine().toUpperCase();
if(test != null && test.length() > 0)
{
quit = test.toUpperCase().charAt(0);
}
else
{
//handle your else here
quit = ' '; //this will keep it from terminating
}
}
将下一行存储在字符串中,然后检查以确保它不为空且长度至少为 1。如果是,则获取第一个字符。如果没有,那么决定你想如何处理这种情况。
我会这样写:
Scanner scan = new Scanner(System.in);
String line;
do{
game.play();
System.out.println("Play again? Press any key to continue, or 'N' to quit");
line = scan.nextLine();
}while (line.isEmpty() || line.toUpperCase().charAt(0) != 'N');
代替quit = scan.nextLine().toUpperCase().charAt(0);
,我们可以这样写:
String str = scan.nextLine().toUpperCase();
quit = ((str == null || "".equals(str)) ? ' ' : str.charAt(0));