提问人:sanjanaa .p.s 提问时间:6/15/2022 最后编辑:Federico klez Cullocasanjanaa .p.s 更新时间:7/10/2022 访问量:73
开关案例未正确执行
Switch cases are not getting executed properly
问:
案例 1 和默认案例无法正常工作,打印语句未执行。我无法识别错误。我不知道扫描仪实现是否有问题,对我来说似乎很好。
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();
}
}
}
答:
0赞
xthe_white_lionx
7/10/2022
#1
只有当条件变为 false 时,您才会退出 while 循环。因此,您的交换机标签“7”是整个交换机中唯一可访问的标签。解决方案是将开关放在 while 循环中。
while(ch!=7){...}
你只需要一个扫描仪,你应该在最后关闭它
public static void main(String[] args) { try { String categoryName = ""; int ch = 0; Scanner sc = 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"); System.out.println(); System.out.print("input: "); ch = sc.nextInt(); switch (ch) { case 1: { System.out.print("enter category name: "); categoryName = sc.nextLine(); sc.nextLine(); while (!ProjectUtility.validateName(categoryName)) { System.out.println("category name must be one word. It cannot contain a numbers,spaces and Alpanumerics."); System.out.print("enter category name: "); categoryName = sc.nextLine(); } break; } case 7: System.out.println("exiting..."); break; default: System.out.println("option not supported"); break; } } sc.close(); } catch (Throwable t) { t.printStackTrace(); } }
评论
while
while
while(ch <= 0 || ch > 7)