IndexOutOfBoundsException error

后端 未结 4 847
栀梦
栀梦 2021-01-29 10:53
public void thisisnotworking()
{
    Scanner input=new Scanner(System.in);
    String cardA;
    String cardB;
    System.out.print(\"Enter Card: \"); cardA=input.nextLi         


        
相关标签:
4条回答
  • 2021-01-29 11:25

    It's hard to say without seeing game, but seems like cardA and cardB are not in game, so game.indexOf(cardA) returns -1 and game.get(-1) throws the exception.

    Also, looking at your code, you search for String in game, and then takes an element from game, which is a String and assigns it to a Card object. You cannot cast from String to any other class than Object, since String is a final class.

    0 讨论(0)
  • 2021-01-29 11:27

    Where do you set the cards into the game? If there is no code missing that might be it, you need to call

    game.set(cardA); 
    game.set(cardB);
    

    before game.get(...);

    0 讨论(0)
  • 2021-01-29 11:28

    Try this...

    public void thisshouldwork()
    {
        Scanner input=new Scanner(System.in);
        String cardA;
        String cardB;
        System.out.print("Enter Card: "); cardA=input.nextLine();
        System.out.print("Enter Card "); cardB=input.nextLine();
        game.add(cardA);
        game.add(cardB);
        Card a = game.get(game.indexOf(cardA));
        Card b = game.get(game.indexOf(cardB));
    

    The problem is you aren't adding cardA or cardB to game so indexOf returns -1 and get throws an IndexOutOfBounds Exception

    0 讨论(0)
  • 2021-01-29 11:30

    You must cast the return value of the readLine method to an Object, and then call the toString() method:

    cardA=((Object)in.readLine()).toString();
    
    0 讨论(0)
提交回复
热议问题