gpt4 book ai didi

java - 开关出现奇怪的错误

转载 作者:行者123 更新时间:2023-12-01 22:05:56 26 4
gpt4 key购买 nike

我创建了一个程序来处理刑事案件并存储它,然后我向它添加了另一个开关,以便我可以访问我希望在程序中添加的其他内容。但是执行选择的时候好像出现了错误。 Switch 不会识别我的选择,而是重复循环内的菜单。编译过程中没有错误。这是编码...

import java.util.ArrayList;
import java.util.Scanner;

public class CriminalCase {




private String batput;
public String getBatput(){return batput;}


public CriminalCase(String batput){
this.batput = batput;

}

private static class robin{
String Batman(){
Scanner s=new Scanner (System.in);
System.out.println();
System.out.println("Enter name.");
String a=s.nextLine();
System.out.println("Enter Date of birth.");
String b=s.nextLine();
System.out.println("Enter Sex.");
String c=s.nextLine();
System.out.println("Enter Crime Committed.");
String d=s.nextLine();
System.out.println("Enter Date of Crime Committed.");
String e=s.nextLine();
System.out.println("Enter Victim.");
String f=s.nextLine();
System.out.println();
String g=""+"\n"+""+"Name:- "+a +"\nDOB:- "+b +"\nSex:- "+c +"\nCrime Committed:- "+d +"\nDate of Crime Committed:- "+e +"\nVictim:- "+f;
System.out.println();
return g;
}
}



public static void main(String[] args) {


ArrayList<CriminalCase> cases = new ArrayList<>();
boolean quit = false;

Scanner s = new Scanner(System.in);

robin j=new robin();
boolean exit=false;
for(;!exit;){
System.out.println("For cases press 1.\nFor printing thank you, press 2.\nTo exit, press 3.");
int choice=s.nextInt();
switch (choice){
case 1:{

while (!quit) {
System.out.println();
System.out.println("To view current cases enter v\nto add a case enter a\nto quit enter q");
String input = s.nextLine();

switch(input){
case ("v"): {
System.out.println("");
System.out.println("The following cases exist:");
System.out.println("\nName:- Batman\nDOB:- Unknown\nSex:- Male\nCrime Committed:- Tresspassing a crime scene, Fleeing scene of crime, Carrying unlicensed vehicles and

weapons.\nDate of Crime Committed:- 18/9/2015\nVictim:- None.");
for (CriminalCase c : cases)
System.out.println(c.getBatput());
break;
}
case("a"):{
String batput=j.Batman();

cases.add(new CriminalCase(batput));
break;
}
case("q"):{
quit = true;


}

}
}
break;
}
case 2:System.out.println("Thank you.");
break;

case 3:exit=true;
}
}
}

}

最佳答案

未经测试,我猜错误就在这段代码中:

int choice=s.nextInt();
switch (choice)
{
case 1:{

while (!quit) {
System.out.println();
System.out.println("To view current cases enter v\nto add a case enter a\nto quit enter q");
String input = s.nextLine();

您正在使用 nextInt() 方法读取整数,然后,您应该像下面这样调用 nextLine()

int choice=s.nextInt();
s.nextLine()
switch (choice)
{
....

看看这个问题来理解这种行为:

Scanner is skipping nextLine() after using next(), nextInt() or other nextFoo() methods

编辑(我的个人建议):

我正在一行中读取单个整数,如下所示:

int choice = Integer.parseInt(s.nextLine());

尝试实现此版本

关于java - 开关出现奇怪的错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32794419/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com