Я пишу программу Java, управляемую меню, для реализации шифрования Vigenere. Для функции меню, я написал следующий код:Ошибка при возврате целого числа вместо Scanner.NextInt()
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)
Я не понимаю, что я делаю неправильно. Может кто-нибудь мне помочь?
Edit: Вот исходный код класса 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();
}
}
Это прекрасно работает для меня, когда я запускаю его. Можете ли вы показать нам еще какой-нибудь код, пожалуйста? – Mureinik