按下按钮时字符串索引超出范围

时间:2014-08-18 01:53:36

标签: java

我正在制作一个小刽子手游戏的问题。

private void btnTActionPerformed(java.awt.event.ActionEvent evt) 
{                                     
    btnT.setEnabled(false);          
    if(word.charAt(0)=='t'){
        lblSpace1.setText("T");
    }
    if(word.charAt(1)=='t'){
        lblSpace2.setText("T");
    }
    if(word.charAt(2)=='t'){
        lblSpace3.setText("T");
    }        
    if(word.charAt(3)=='t'){
        lblSpace4.setText("T");
    }        
    if(word.charAt(4)=='t'){
        lblSpace5.setText("T");
    }        
    if(word.charAt(5)=='t'){
        lblSpace6.setText("T");
    }        
    if(word.charAt(6)=='t'){
        lblSpace7.setText("T");
    }        
    if(word.charAt(7)=='t'){
        lblSpace8.setText("T");
    }        
    if(word.charAt(8)=='t'){
        lblSpace9.setText("T");
    }        
    if(word.charAt(9)=='t'){
        lblSpace10.setText("T");
    }
    if(!word.contains("t")){
        guessesLeft--;
        lblGuessesleft.setText("Number: "+guessesLeft+"");            
    }
}

代码检查字母t是否在单词的每个空格中。但是,有些单词的长度不是10个字符,因此会打印错误“String index out of range”。

有没有办法只检查word中的字母?

3 个答案:

答案 0 :(得分:0)

您可以简单地执行以下操作:

@Override
public void actionPerformed(ActionEvent e)
{

    for(int i = 0; i < word.length(); ++i)

        if(word.charAt(i) == 't')//if this condition is true
        {                  //that means the character is at the position `i`
            switch (i)
            {
                case 1:
                    lblSpace1.setText("T");
                    break;
                case 2:
                    // do other stuff
                    break;
                default:
                    break;
            }
        }
}

使用此代码,您不能遇到IndexOutOfRange类型的问题。

答案 1 :(得分:0)

我建议您多读一些基本数据结构,如数组以及基本forwhile循环。这将有助于您在游戏中发挥极大的作用。

这里有一个从哪里开始的想法:

int word_length = word.length();
char input = 't'; //instead of hard coding t, try getting the user input from somewhere


for( int i=0; i< word_length; i++ )
{
    if( word.charAt(i) == input )
    {
        //do stuff with labels
    }
}

答案 2 :(得分:-2)

您可能需要关注的另一种风味是Java 8,您可以执行此操作

public void actionPerformed(ActionEvent e)
{
    String s = "TTTTT";
       List<String> list = Arrays.asList(s.split(""));
       list.stream()
           .filter( st -> st.equals("T"))
           .forEach(st -> System.out.println(" I am T"));

   IntStream.range(0, list.size())
             .filter(index -> list.get(index).equals("T"))
             .forEach(index -> System.out.println("The poistion is " + index));
}

输出:

 I am T
 I am T
 I am T
 I am T
 I am T
The poistion is 0
The poistion is 1
The poistion is 2
The poistion is 3
The poistion is 4

<强> Explantion

使用split和regex“”将字符串s转换为列表,并且list使用具有过滤器的流类,其行为类似于if子句,并且如果字符串st等于T;对于每一个for循环System.out我都是T in out或者你可以随心所欲。

第二个答案就像for循环,因此您可以访问索引及其项目