Java 返回整数而不是Scanner.NextInt()时出错
我正在编写一个菜单驱动的Java程序来实现Vigenere密码。 对于菜单功能,我编写了以下代码:Java 返回整数而不是Scanner.NextInt()时出错,java,return,java.util.scanner,Java,Return,Java.util.scanner,我正在编写一个菜单驱动的Java程序来实现Vigenere密码。 对于菜单功能,我编写了以下代码: 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?"
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();
}
现在这项工作做得不错,但我的教授批评我没有关闭扫描器类对象“扫描”。
因此,我对我的代码进行了以下编辑:
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();
}
选中此项:当我运行它时,它对我来说很好。你能给我们看更多的代码吗?我明白了,所以我想我应该初始化Cipherman类本身中的“scan”变量,然后简单地使用这个。当我使用一个方法时,扫描,然后?是正确的。当您关闭扫描仪时,它也将关闭System.in stream,您将无法再从System.in读取数据,即,您将无法再次使用新的扫描仪。