gpt4 book ai didi

java - 线程中的异常 "main"java.lang.ArrayIndexOutOfBoundsException : 1 at beerregister. BeerRegister.list(BeerRegister.java:66)

转载 作者:行者123 更新时间:2023-12-01 04:18:44 24 4
gpt4 key购买 nike

我的错误:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
at beerregister.BeerRegister.list(BeerRegister.java:66)

如何修复它?

我的代码有点难看,抱歉。

package beerregister;

import java.util.*;
import beerregister.BeerRegister.NameComparator;

public class BeerRegister{

public String name;
public String style;
public String alc;

List<BeerRegister> bb = new ArrayList<BeerRegister>();

int szamlalo = 0;
//private StyleComparator sc;
//private AlcComparator ac;

public BeerRegister(){

Scanner sc = new Scanner(System.in);
String cmd[];
System.out.println("Lökjed:");
while(true){
cmd = sc.nextLine().split(" ");
if(cmd[0].equals("add")) {add(cmd[1],cmd[2],cmd[3]);}
if(cmd[0].equals("list")) {list(cmd);}
}
}
public BeerRegister(String name, String style, String alc){
this.name=name;
this.style=style;
this.alc=alc;
}

public void add(String name,String style,String alc){
BeerRegister br = new BeerRegister(name, style, alc);
// br.name = name;
// br.style = style;
// br.alc = alc;
bb.add(br);
}

public void list(String[] cmd){

System.out.println(bb.size());
//synchronized(bb){}
if(cmd[1].equals("name"))
Collections.sort(bb,new NameComparator());
//if(cmd[1].equals("style")) StyleComparator();
//if(cmd[1].equals("alc")) AlcComparator();

for(int i = 0; i < bb.size();i++){
System.out.println(bb.get(i).name+ " "+ bb.get(i).style + " " + bb.get(i).alc);

}
}

class NameComparator implements Comparator<BeerRegister>{
@Override
public int compare(BeerRegister a, BeerRegister b) {
return a.name.compareToIgnoreCase(b.name);
}
}
public static void main( String [] args){
BeerRegister xyz = new BeerRegister();
}
}

那么我该如何解决我的问题呢?请帮忙。

最佳答案

要解决您的问题,请在 BeerRegister 方法中添加一些条件,如下所示:

        if (cmd.length > 3 && cmd[0].equals("add")) {
add(cmd[1], cmd[2], cmd[3]);
}else{
System.out.println("Rewrite CMD Please!");
}
if (cmd.length > 1 && cmd[0].equals("list")) {
list(cmd);
}

关于java - 线程中的异常 "main"java.lang.ArrayIndexOutOfBoundsException : 1 at beerregister. BeerRegister.list(BeerRegister.java:66),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19190853/

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