【问题标题】:User Cannot Enter Text, Index Out Of Bounds Exception用户无法输入文本,索引超出范围异常
【发布时间】:2015-05-01 20:58:17
【问题描述】:

我的代码运行,但是当用户在文本字段中输入文本时,我得到了一个超出范围的异常。我认为这与我给空框赋值的这行代码有关:int express = (str != null && !"".equals(str)) ? Integer.parseInt(str) : -1; 但我不确定。有没有不同的方法可以做到这一点?代码如下:

import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.image.Image;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Pane;
import javafx.stage.Stage;
import javafx.scene.image.ImageView;

import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedList;
import java.util.concurrent.atomic.AtomicReference;

public class Main extends Application {

   @Override
   public void start(Stage primaryStage) {


      ArrayList<Integer> deck;
      deck = new ArrayList<>();
      int i = 1;
      while(i < 52){
         deck.add(i);
         i++;
      }
      final AtomicReference<String> result = new AtomicReference<>("go.");

      Collections.shuffle(deck);

      BorderPane pane = new BorderPane();

      HBox top = new HBox(10);
      Label display = new Label(result.toString());
      Button btShuffle = new Button("Shuffle");

      top.getChildren().add(display);
      top.getChildren().add(btShuffle);


      HBox center = new HBox(10);
      Card card1 = new Card(deck.get(0));
      center.getChildren().add(card1);

      Card card2 = new Card(deck.get(1));
      center.getChildren().add(card2);

      Card card3 = new Card(deck.get(12));
      center.getChildren().add(card3);

      Card card4 = new Card(deck.get(14));
      center.getChildren().add(card4);



      btShuffle.setOnAction(
            e -> {
               Collections.shuffle(deck);
              center.getChildren().clear();    
              center.getChildren().add(new Card(deck.get(0)));
              center.getChildren().add(new Card(deck.get(1)));
              center.getChildren().add(new Card(deck.get(2)));
              center.getChildren().add(new Card(deck.get(3)));

            });





      HBox bottom = new HBox(10);
      Label expression = new Label("Please Enter the expression: ");

      TextField tfExpress = new TextField();
      LinkedList<Object> expInput = new LinkedList<>();
      ArrayList<Character> signs = new ArrayList<>();
      signs.add('/');
      signs.add('+');
      signs.add('(');
      signs.add(')');
      signs.add('-');
      signs.add('^');
      signs.add('*');
      signs.add('%');
      String str = tfExpress.getText();
      char tempStor[] = str.toCharArray();
      for(char c: tempStor){
         expInput.add(c);
      }

      int express = (str != null && !"".equals(str)) ? Integer.parseInt(str) : -1;      



      expInput.removeIf(p-> p.equals(signs));

      Button btVerify = new Button("Verify");
      bottom.getChildren().add(expression);
      bottom.getChildren().add(tfExpress);
      bottom.getChildren().add(btVerify);

      btVerify.setOnAction(
            (ActionEvent e) -> {
               if(card1.CardValue() == (int)expInput.get(0)
               && card2.CardValue() == (int)expInput.get(1)
               && card3.CardValue() == (int)expInput.get(2)
               && card4.CardValue() == (int)expInput.get(3)){
                  if(express == 24){
                     result.set("Correct");
                  }
                  else
                     result.set("Incorrect");

               }
               else
                  result.set("The numbers in the expression don't "
                     + "match the numbers in the set.");
            });

      pane.setTop(top);
      pane.setCenter(center);
      pane.setBottom(bottom);

      Scene scene = new Scene(pane);
      primaryStage.setTitle("24 card game");
      primaryStage.setScene(scene);
      primaryStage.show();
   }

   public class Card extends Pane {
      public int cardVal;
      Card(int card){
         Image cardImage;
         cardImage = new Image("card/"+ card +".png");
         getChildren().add(new ImageView(cardImage));
         cardVal = card;

      }

      public int CardValue(){
         int card = 0;

         if(cardVal <= 13){
            card = cardVal;
         }
         else if(cardVal > 13 && cardVal <= 26){
            card = cardVal - 13;
         }
         else if(cardVal > 26 && cardVal <= 39){
            card = cardVal - 26;
         }
         else if(cardVal > 39 && cardVal <= 52){
            card = cardVal - 39;
         }


         return card;
      }




   }



   public static void main(String[] args) {
      launch(args);
   }

}

这里是例外:

Exception in thread "JavaFX Application Thread" java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
    at java.util.LinkedList.checkElementIndex(LinkedList.java:555)
    at java.util.LinkedList.get(LinkedList.java:476)
    at Main.lambda$start$2(Main.java:109)
    at Main$$Lambda$74/1787879.handle(Unknown Source)
    at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:86)
    at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:238)
    at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:191)
    at com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEventDispatcher.java:59)
    at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:58)
    at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
    at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
    at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:74)
    at com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:49)
    at javafx.event.Event.fireEvent(Event.java:198)
    at javafx.scene.Node.fireEvent(Node.java:8216)
    at javafx.scene.control.Button.fire(Button.java:185)
    at com.sun.javafx.scene.control.behavior.ButtonBehavior.mouseReleased(ButtonBehavior.java:182)
    at com.sun.javafx.scene.control.skin.BehaviorSkinBase$1.handle(BehaviorSkinBase.java:96)
    at com.sun.javafx.scene.control.skin.BehaviorSkinBase$1.handle(BehaviorSkinBase.java:89)
    at com.sun.javafx.event.CompositeEventHandler$NormalEventHandlerRecord.handleBubblingEvent(CompositeEventHandler.java:218)
    at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:80)
    at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:238)
    at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:191)
    at com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEventDispatcher.java:59)
    at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:58)
    at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
    at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
    at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:74)
    at com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:54)
    at javafx.event.Event.fireEvent(Event.java:198)
    at javafx.scene.Scene$MouseHandler.process(Scene.java:3724)
    at javafx.scene.Scene$MouseHandler.access$1500(Scene.java:3452)
    at javafx.scene.Scene.impl_processMouseEvent(Scene.java:1728)
    at javafx.scene.Scene$ScenePeerListener.mouseEvent(Scene.java:2461)
    at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:348)
    at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:273)
    at java.security.AccessController.doPrivileged(Native Method)
    at com.sun.javafx.tk.quantum.GlassViewEventHandler.handleMouseEvent(GlassViewEventHandler.java:382)
    at com.sun.glass.ui.View.handleMouseEvent(View.java:553)
    at com.sun.glass.ui.View.notifyMouse(View.java:925)
    at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
    at com.sun.glass.ui.win.WinApplication.lambda$null$141(WinApplication.java:102)
    at com.sun.glass.ui.win.WinApplication$$Lambda$38/2075313.run(Unknown Source)
    at java.lang.Thread.run(Thread.java:745)

【问题讨论】:

  • 这些是拼写错误吗:Card card3 = new Card(deck.get(12));Card card4 = new Card(deck.get(14));(我的意思是使用索引 1214)?
  • 不完全是。我只是在搞乱不同的索引。我使用哪个重要吗?我的随机播放按钮工作正常。
  • 好的,这并没有造成问题,因为牌组有 52 个项目。所有神奇的数字使代码有点难以理解..
  • 在“char tempStor[] = str.toCharArray();”上添加断点行,调试并检查数组的内容。还要检查 tfExpress.getText();正在返回一个空字符串

标签: java arraylist javafx textfield indexoutofboundsexception


【解决方案1】:

失败在

btVerify.setOnAction(
        (ActionEvent e) -> {
           if(card1.CardValue() == (int)expInput.get(0)

您上面的某些行创建了一个新的 LinkedList,因此其中没有任何值。这会导致异常。

编辑:作为对某些 cmets 的回复。一个可能的解决方案可能如下所示: (无需进一步必要的重构;))

final 
btVerify.setOnAction(
    (ActionEvent e) -> {
            LinkedList<Character> expInput = new LinkedList<Character>();
            for(char c: tfExpress.getText().toCharArray()){
                expInput.add(c);
            }

            if(card1.CardValue() == Integer.valueOf(expInput.get(0))
                 && card2.CardValue() == Integer.valueOf(expInput.get(1) )
                 && card3.CardValue() == Integer.valueOf(expInput.get(2))
                 && card4.CardValue() == Integer.valueOf(expInput.get(3))){
                 if(express == 24){
                     result.set("Correct");
                 }
                 else
                    result.set("Incorrect");

             }
             else
                 result.set("The numbers in the expression don't "
                            + "match the numbers in the set.");
         });

【讨论】:

  • 你提到的那行下面的几行是 for(char c: tempStor){ expInput.add(c);所以确实链表不是空的,除非 tempStor[] 是 emtpty
  • 这只是部分正确,因为循环永远不会被执行。 tempStore 中的字符是新创建的 TextField 中的字符,可能包含零个字符..
  • 我的例外是说我的列表大小为 0 对吗?那么我可以如何扩展它吗? @LalitRao
  • 向列表中添加一些内容。我在 atm 所做的一切都是静态代码分析。如果我是正确的,解决方案类似于:直接在 lamda 表达式中调用 TextField。
  • 非常感谢!我的验证按钮不再给出错误。现在由于某种原因,当我输入值时我的 AtomiceReference 不会改变。这可能是因为它放置在哪里?
猜你喜欢
  • 2018-03-02
  • 2011-03-16
  • 1970-01-01
  • 1970-01-01
  • 2011-12-25
  • 2023-04-10
相关资源
最近更新 更多