我用 JAVA 语言编写了一个程序,它通过使用 Scanner 类接受来自控制台的输入......
现在我想将此功能添加到我的代码中,以便在用户按下 Esc 按钮时存在循环(while)。到目前为止,我认为键盘类可以帮助我,但它就像扫描仪......我尝试使用事件但不知道如何正确使用它们......
源代码:
package switchCase_v1;
import cs1.Keyboard;
import java.util.EventObject;
import java.awt.AWTEvent;
import java.awt.event.KeyEvent;
import java.awt.event.ComponentEvent;
import java.awt.event.InputEvent;
import java.util.*;
public class SwithCase {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input = new Scanner(System.in);
System.out.println("enter the name or number of month: ");
int monthNumber = input.nextInt();
while (true) {
KeyEvent button;
if (button.getKeyCode() == 27)
break;
else if (monthNumber == '\n') {
System.out.println("enter a number");
monthNumber = input.nextInt();
} else {
switch (monthNumber) {
case 1:
case 2:
case 3:
case 4:
case 5:
case 6:
System.out.println("it has 31 days");
monthNumber = input.nextInt();
break;
case 7:
case 8:
case 9:
case 10:
case 11:
case 12:
System.out.println("it has 30 days");
monthNumber = input.nextInt();
break;
default:
System.out.println("it is not a valid number");
monthNumber = input.nextInt();
break;
}
}
}
}
}
当我想考虑“Esc”或“Enter”等点击按钮时,我该如何处理?我认为它也应该适用于使用 ASCII 码。
这是我的代码的新版本:
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input = new Scanner(System.in);
System.out.print("Check number of days");
KeyEvent e;
if (e.getKeyCode() == KeyEvent.VK_ENTER)
{
System.out.println("enter the name or number of month: ");
int monthNumber=input.nextInt();
}
else if (Keyboard.getEventKey()==Keyboard.KEY_ESCAPE)
{
System.out.println("GoodBye");
}
}
}
但它有一个错误说 e 对象可能没有被初始化......!!!!!我该怎么办?!