我正在编写一个菜单驱动的 Java 程序来实现维吉尼亚密码。 对于菜单功能,我编写了以下代码:
public static int printmenu(){
Scanner scan = new Scanner(System.in);
System.out.println("Welcome to the Vigenere Cipher!");
System.out.println("What would you like to do?");
System.out.println("1.Encrypt a message");
System.out.println("2.Decrypt a message");
System.out.println("Enter your choice:");
return scan.nextInt();
}
现在这可以正确完成工作,但我因没有关闭我的扫描仪类对象“scan”而受到教授的批评。 因此,我对代码进行了以下编辑:
public static int printmenu(){
int a;
Scanner scan = new Scanner(System.in);
System.out.println("Welcome to the Vigenere Cipher!");
System.out.println("What would you like to do?");
System.out.println("1.Encrypt a message");
System.out.println("2.Decrypt a message");
System.out.println("Enter your choice:");
a = scan.nextInt();
scan.close();
return a;
}
但是,这会返回以下错误:
Exception in thread "main" java.util.NoSuchElementException: No line found
at java.util.Scanner.nextLine(Unknown Source)
at vigenere.Ciphermain.main(Ciphermain.java:30)
我不明白我做错了什么。谁能帮我吗?
编辑:这是 Ciphermain 类的源代码:
public class Ciphermain extends JFrame{
public static int printmenu(){
int a;
Scanner scan = new Scanner(System.in);
System.out.println("Welcome to the Vigenere Cipher!");
System.out.println("What would you like to do?");
System.out.println("1.Encrypt a message");
System.out.println("2.Decrypt a message");
System.out.println("Enter your choice:");
a = scan.nextInt();
scan.close();
return a;
}
public static void main(String[] args) {
String message, key;
int choice;
choice = printmenu();
Scanner scan = new Scanner(System.in);
if(choice == 1){
System.out.println("Enter the message to be encrypted:");
message = scan.nextLine();
System.out.println("Enter the secret key:");
key = scan.next();
Cipher ciph = new Cipher(key);
System.out.println("Encrypted message is: " + ciph.encrypt(message));
}
else{
System.out.println("Enter the message to be decrypted:");
message = scan.nextLine();
System.out.println("Enter the secret key:");
key = scan.next();
Cipher ciph = new Cipher(key);
System.out.println("Decrypted message is: " + ciph.decrypt(message));
}
scan.close();
}
}
最佳答案
关闭扫描器将关闭底层流(System.in)。因此,下次您在已关闭的 System.in 上创建扫描程序时,您将得到这样的异常。
在程序开始时创建扫描仪,在任何地方使用它并在程序结束时关闭它。
喜欢:
static Scanner scan;
static int displayMenu(){
// display menu.
return scan.nextInt();
}
public static void main(String [] args){
scan = new Scanner(System.in);
// start work.
// end of work.
scan.close();
}
检查这个:http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#close()
关于java - 返回整数而不是 Scanner.NextInt() 时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26366858/