java - 字符串数组错误

标签 java arrays string println

我遇到一个数组错误,说它超出范围,我不知道出了什么问题。这是我的代码:

import java.util.*;
public class gameVar {
    public static int size;
    public static int counter;
    public static Scanner input = new Scanner(System.in);
    public static String currentIn;
    public static String nameArray[] = new String[size];
}

和第二类(我在第 6 行收到错误):

public class mainThread extends gameVar {
public static void main(String[] args){
    System.out.println("Please type the desired amount of players: ");
    size = input.nextInt();
    for(int counter = 0; counter < size; counter++){
        System.out.println("Please enter the name of player " + nameArray[counter])
        }
    }
}

非常感谢您的帮助!

最佳答案

以下分配零元素数组:

public static int size;
public static String nameArray[] = new String[size]; // <<<< Here, `size` is zero

您需要将数组初始化移至main():

public static void main(String[] args){
    System.out.println("Please type the desired amount of players: ");
    size = input.nextInt();
    nameArray = new String[size]; // <<< THIS
    for(int counter = 0; counter < size; counter++){
        System.out.println("Please enter the name of player " + nameArray[counter])
        }
    }
}

然后,您可以从 nameArray 的声明中删除 = new String[size]

关于java - 字符串数组错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15596461/

相关文章:

java - 在java中打印带有空字符的字符串

java - angularjs如何接收从tomcat servlet发送的json消息

java - 为什么 WebMvcConfigurer 重写方法不起作用?

C 将 char * 复制到 char[]

java - Piglatin,难以理解如何在字符串中移动 '.'

将特殊字符 * 重新插入字符串中的预定义位置

java - 在文本区域插入非常大的字符串时,浏览器不支持 : selenium :java

c - 使用 %s(即字符串说明符)读取 char 数组

php - Checkbox null表示不是,checkbox checked是1

Python:字符串反转中途停止