gpt4 book ai didi

java - 如果不使用 "return;",如何突破 void 方法

转载 作者:行者123 更新时间:2023-11-29 10:12:01 25 4
gpt4 key购买 nike

如何跳出 void 方法并返回到 switch 方法?

    public static void decrypt() throws FileNotFoundException {
Scanner kbrd = new Scanner(System.in);
System.out.println("Enter Key-file name: ");
String filename = kbrd.nextLine();
System.out.println("Enter Message-filename: ");
String mssgFilename = kbrd.nextLine();
String[] keyArray = loadMessage(filename);
String[] message = loadMessage(mssgFilename);
String[] cipher = xor2(message, keyArray);
String readable = showText(cipher);
System.out.println("The text:" + readable);
return;
}

然后这里是switch方法

    System.out.println("Encrypt  1.");
System.out.println("Decrypt 2.");
System.out.println("Make Key 3.");
System.out.println("Quit 4.");
Scanner scan = new Scanner(System.in);
String choice = scan.nextLine();

do {
switch (choice) {
case "1":
encrypt();
break;
case "2":
decrypt();
break;
case "3":
makeKey();
break;

}

} while (choice != "4");

问题是,无论我选择什么,它都保留在那个方法中,尽管最后有 return 语句,这不应该让我回到 switch 方法吗?

最佳答案

将添加另一个选择的能力放入循环中。您目前正在进入一个无限循环,因为 choice 没有改变。

String choice;
do {
choice = scanner.nextLine();
switch (choice) {
case "1":
encrypt();
break;
case "2":
decrypt();
break;
case "3":
makeKey();
break;
}
} while (!choice.equals("4"));

注意这与被调用的方法无关;这完全由 do...while 循环控制。

关于java - 如果不使用 "return;",如何突破 void 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29910280/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com