我希望我的程序一遍又一遍地遍历选项(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();
}
}
答案 0 :(得分:1)
请勿在阅读选项中使用循环,而是使用 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;
}
答案 1 :(得分:1)
不要使用System.in创建多个扫描程序,因为如果关闭扫描程序,则可能会关闭System.in本身并弄乱所有此类扫描程序功能。
而是使用一个且只有一个使用System.in构建的Scanner,并在需要的程序中共享它,并且只有在程序完全使用它时才关闭它。
答案 2 :(得分:-1)
请改为尝试:
import java.util.Scanner;
class Main {
public static void main(String args[]){
Scanner s = new Scanner(System.in);
int option;
while(((option=s.nextInt())<4)&&(option>0))
{
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");
}
}
}