我希望程序反复遍历选项(1,2,3),以便可以多次执行这些功能。但是,在键入一个选项的输入后,程序将终止。如何使它循环多次而不终止?
这是当前示例输入和输出:
1-输入
2-查找
3-黑名单
3
输入列入黑名单的IPA:232
(然后终止)
import java.util.*;
public class Main {
public static void main(String[] args) {
DNS a = new DNS();
String domain;
String ipa;
System.out.printf("1 - Input\n");
System.out.printf("2 - Look up\n");
System.out.printf("3 - Blacklist\n");
Scanner scan = new Scanner(System.in);
while ( scan.hasNextInt() ) {
int option = scan.nextInt();
if(option == 1){
System.out.printf("Enter Domain & IPA: ");
Scanner scan1 = new Scanner(System.in);
String theLine = scan1.nextLine();
String[] split = theLine.split(" ");
domain = split[0];
ipa = split[1];
a.input(domain, ipa);
scan1.close();
} else if (option == 2){
System.out.printf("Enter Domain: ");
Scanner scan2 = new Scanner(System.in);
String theLine = scan2.nextLine();
domain = theLine;
ipa = a.lookup(domain);
if(ipa.equals("null")){
System.out.printf("There is no IPA for %s\n", domain);
} else {
System.out.printf("The IPA for %s is %s\n", domain, ipa);
}
scan2.close();
} else if (option == 3){
System.out.printf("Enter Blacklisted IPA: ");
Scanner scan3 = new Scanner(System.in);
String theLine = scan3.nextLine();
ipa = theLine;
a.blacklist(ipa);
scan3.close();
} else {
System.out.printf("Incorrect command input\n");
}
}
scan.close();
}
}
最佳答案
不要在阅读选项中使用循环,而应使用 switch-case
。
您不能使用循环来迭代printf
输出:)
Scanner scan = new Scanner(System.in);
int option = scan.nextInt();
switch(option){
case 1:{//input your argument 1 here}break;
case 2:{//input your argument 2 here}break;
case 3:{//input your argument 3 here}break;
}
关于java - Java程序终止而不是遍历选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40066616/