【问题标题】:My code is giving java.lang.StringIndexOutOfBoundsException and Command exited with non - zero status [duplicate]我的代码给出了 java.lang.StringIndexOutOfBoundsException 和 Command exited with non-zero status [重复]
【发布时间】:2019-05-20 02:13:10
【问题描述】:

我是一名初学者,自学成才,尝试通过作业完成工作。我试图创建一个程序,该程序将根据输入的第一行(这是一个整数)读取 N 行代码。其他输入行由三个字母组成的行,可以是 b、s 或 f。 B 和 S 是唯一被读取的重要字母,因为 B 给滚动的玩家加一分,超过 3 个 S 并且玩家失去回合,F 没有任何意义。根据阅读的字母,每轮为每个人分配点数。我当前的障碍是 char d1 = line[i].charAt(0) 区域,它给了我一个以非零状态退出的命令,并且在线程“main”java.lang.StringIndexOutOfBoundsException 中出现异常:字符串索引超出范围: 2.
int num = input.nextInt(); String [] line = new String[num];

for (int i=0; i<num; i++){
ine[i] = input.next(); 


// Creating characters for the dice 
char d1 = line[i].charAt(0);
char d2 = line[i].charAt(2);
char d3 = line[i].charAt(4);

while (aliceScore<3){

//D1 die score - alice
if (d1 == 'b')
aliceScore++;
else if (d1 == 's') 
aliceShotgun++;
else 

//D2 die score - Alice
if (d2 == 'b')
aliceScore++;
else if (d2 == 's')
aliceShotgun++;
else 

//D3 die score - Alice
if (d3 == 'b')
aliceScore++;
else if (d2 == 's')
aliceShotgun++;
else 


if  (aliceShotgun == 3)
aliceScore = 0;
break;  

我希望它读取输入的每一行并将 d1、d2 和 d3 分配给每行中的三个字母,然后可以基于此将点分配给每个人。一个示例输入是

3
B B S
S B F
B B F

输出 爱丽丝:3,鲍勃:2

【问题讨论】:

  • ine[i] = input.next(); - 可能改成line[i] = input.nextLine():
  • 如果上面写着String index out of range: 2.,你确定不是line[i].charAt(2) ??
  • 能否显示控制台输入和错误。
  • 请注意,“重复”谈到数组索引越界。但是,当在字符串中进行索引时,该内容也非常适用。

标签: java arrays string for-loop char


【解决方案1】:

input.next(); 更改为input.nextLine()

简而言之,input.next() 只会给你一个单词,而input.nextLine() 会扫描整行。您也可以尝试自己调试它,看看每个代码块/代码行中发生了什么。

注意:确保您的输入正确且每行至少包含 5 个字符 (line[i].charAt(4))。否则你会再次得到java.lang.StringIndexOutOfBoundsException。看看为什么会这样:understanding-array-indexoutofbounds-exception-in-java

【讨论】:

    【解决方案2】:

    input.next() 只能读取字母到空格,所以而不是input.next() 您可以将其更改为 input.nextLine()

    例如:

    for (int i=0; i<num; i++){    
       ine[i] = input.nextLine();    
       String [] a=ine[i].split(" ");    
       char d1 = a[0].charAt(0);    
       char d2 = a[1].charAt(0);    
       char d3 = a[2].charAt(0);
    }
    

    【讨论】:

      猜你喜欢
      • 2020-11-25
      • 1970-01-01
      • 2017-04-07
      • 1970-01-01
      • 1970-01-01
      • 2021-12-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多