简体   繁体   中英

Basic for loop manipulation of java array?

I'm new to Java, obviously, and am working on homework where I'm given an array and then have to mentally manipulate it with various for loops several times. I've completed my work however I, being new to and excited about computer science, figured I could write a basic program to check my work.

This is the code I've written and my compiler keeps yelling at me that it "cannot find symbol - variable a" towards the bottom there. My ignorant thinking tells me that I created "a" when I named the array "a". Sadly I haven't been able to find an example code similar to this. Can you guys tell me what I'm doing wrong?

import java.util.Scanner;

public class ArrayTest
{
public static void main(String[] args)
{
int[] a = { 1, 2, 3, 4, 5, 4, 3, 2, 1, 0 };// the array I'm working on

}
{
for (int i = 1; i < 10; i++) { a[i] = a[i - 1]; } //the manipulation given
}
{   
System.out.println(a[i]);
}
}

Thank you!

Your a array is declared as a local member of your main method.

The next blocks after your main method are called instance blocks, because they relate to an instance of your Main class rather than to the body of its main , static, executable method.

Because of that, your for loop references a variable whose scope cannot be accessed.

Move your for loop and the printout to the main method by removing the curly brackets surrounding them in order for your code to compile.

edit just as in Keppil's answer.

As requested, a bare copy-paste of Keppil's code.

public static void main(final String[] args) {
    int[] a = { 1, 2, 3, 4, 5, 4, 3, 2, 1, 0 };// the array I'm working on
    for (int i = 1; i < 10; i++) {
        a[i] = a[i - 1]; // the manipulation given
        System.out.println(a[i]);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM