如果不使用 "return;",如何突破 void 方法
how to break out of a void method, if not with "return;"
如何跳出 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;
}
然后这里是切换方法
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 循环控制。
你有一个进入无限循环的循环,因为选择只读一次。您输入 3 一次,它会进入条件 choice != '4'
的循环,并且它始终为真,因为您不会更改您的选择。所以你的函数被一遍又一遍地调用。 (它 确实突破了 函数,但它被一遍又一遍地调用)将输入行放在循环中。
如何跳出 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;
}
然后这里是切换方法
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 循环控制。
你有一个进入无限循环的循环,因为选择只读一次。您输入 3 一次,它会进入条件 choice != '4'
的循环,并且它始终为真,因为您不会更改您的选择。所以你的函数被一遍又一遍地调用。 (它 确实突破了 函数,但它被一遍又一遍地调用)将输入行放在循环中。