【发布时间】:2022-06-15 01:05:56
【问题描述】:
case 1 和 default case 不能正常工作 print 语句没有被执行。我无法识别错误。我不知道扫描仪实现是否有问题,对我来说似乎很好。
import java.util.*;
public class StartApp {
public static void main(String[] args) {
try {
String categoryName="";
int ch=0;
Scanner sc1=new Scanner(System.in);
Scanner sc2=new Scanner(System.in);
Logger.getInstance().log("Starting task manager", 1);
while(ch!=7)
{
System.out.println("press 1 to create category");
System.out.println("press 2 to load category");
System.out.println("press 3 to remove catergory");
System.out.println("press 4 to list category");
System.out.println("press 5 to search category");
System.out.println("press 6 to export");
System.out.println("press 7 to exit");
ch=sc1.nextInt();
}
switch(ch)
{
case 1:{
System.out.println("enter category name");
categoryName=sc2.nextLine();
sc2.nextLine();
while(!ProjectUtility.validateName(categoryName))
{
System.out.println("category name must be one word. It cannot contain a numbers,spaces and Alpanumerics.");
categoryName=sc2.nextLine();
}
break;}
case 7:
System.out.println("exiting...");
break;
default:
System.out.println("option not supported");
break;
}
}
catch(Throwable t)
{
t.printStackTrace();
}
}
}
【问题讨论】:
-
在我看来,除非您选择 7,否则您将被困在第一个
while中 -
可能问题在于在同一个输入源上使用两个
Scanners,因此它们会互相拿走项目。 -
@akarnokd 他们永远不会使用第二个扫描仪,除非他们在第一个输入中选择“7”,然后立即结束程序。我的印象(特别是从不稳定的缩进来看)是他们把
while循环的右括号放得太早了。
标签: java while-loop switch-statement java.util.scanner