如何从for循环打印数组?

时间:2017-03-20 03:47:06

标签: java arrays loops for-loop multidimensional-array

编写简历构建器。我陷入了必须与每所学校相对应的描述部分,但是对用户输入有所不同(用户确定每个学校有多少描述点)。每次我尝试从这个循环打印时,我都会收到一个错误,即找不到该变量。怎么解决?

输入学校的循环:

//numberOfSchools is int entered by user

for (int i = 0; i < numberOfSchools; i++) {
        System.out.println("What was school " + (i + 1) + " name?");
        schoolInfo[i][0] = scan.nextLine();
        System.out.println("Where was " + schoolInfo[i][0] + " ?");
        schoolInfo[i][1] = scan.nextLine();
        System.out.println("What was your start date at " + schoolInfo[i][0]);
        schoolInfo[i][2] = scan.nextLine();
        System.out.println("What was your end date at " + schoolInfo[i][0] +
                "enter 'present' if still attending");
        schoolInfo[i][3] = scan.nextLine();

        System.out.println("How many description points would you like to add for School" + i);
        int eduDescAmount = scan.nextInt();
        String eduDesc[][] = new String[numberOfSchools][eduDescAmount];
        scan.nextLine();
        for(int j = 0; j < eduDescAmount; j++){
            System.out.println("Enter detail " + (j+1) + " for " + schoolInfo[i][0]);
            eduDesc[i][j] = scan.nextLine();
        }
    }

打印循环:

for (int r = 0; r < schoolInfo.length; r++) {
        for (int q = 0; q < schoolInfo.length; q++){
            System.out.println(eduDesc[r][q]);
        }

3 个答案:

答案 0 :(得分:0)

每次迭代都会在eduDesc循环中再次声明

for。它也只在循环内可见。以下是正确的结构:

String[][] eduDesc = new String[numberOfSchools][];
for (int i = 0; i < numberOfSchools; i++) {
    ...
    int eduDescAmount = scan.nextInt();
    eduDesc[i] = new String[eduDescAmount];
    ...
}

答案 1 :(得分:0)

eduDesc变量不在打印循环的范围内。每次打开块时,例如,在方法体,循环或条件中,都会输入内部范围。这可以访问外部作用域中的所有变量,但是一旦退出块,其中定义的任何内容都不在范围内。

在两个循环可以访问的作用域中声明eduDesc变量,方法是在第一个循环之前声明它,并且您将能够访问它。

答案 2 :(得分:0)

我猜问题在于eduDesc变量的范围。当你写:

for (int i = 0; i < numberOfSchools; i++) {
    /* Your Code */
    int eduDescAmount = scan.nextInt();
    String eduDesc[][] = new String[numberOfSchools][eduDescAmount]; // This means eduDesc[][] is declared as a local variable
    /* More code */
}

通过局部变量,我指的是一个变量,其范围限制在定义范围内。在您的情况下,变量eduDesc[][]for循环内声明,这意味着它只能在for循环中访问。
一旦JVM完成for循环的执行,变量eduDesc[][]就不再可访问了,所以如果在尝试访问变量时循环外的任何代码,编译器会抱怨,“哇!那个变量是在一个范围内声明的一个for循环,它本地只到那个块!!“。

解决方案是在循环之外声明它:

int numberOfSchools = `some int`;
String eduDesc[][] = new String[numberOfSchools][]; 
for (int i = 0; i < numberOfSchools; i++) {
    /* n No of schooling work */
    eduDescAmount = scan.nextInt();
    /* More schooling here */
}

希望这个答案。