0

Hi, will someone please tell me whats wrong with my java code, im and absolute newb just trying to write a program that works.

As i said, i'm very new to Java. I've learned python before so i know some programming concepts, i'm trying to write a stupid program that kind of mocks shorthand compression. Literally just simulates it. I know that there is a lot of holes in the way this works, but like i said i just want to make something work. Eventually i want the program to read the amount of repeated characters then put that amount as well as the character. For example: If their are 7 0's, print 70. 7 being the amount of the character and 0 being the character. The code: class myCompression { static void alg() { int[] arr = {0,0,0,0,0,0,0}; for(int i: arr) { if (i==0) { int[] data = new int[arr.length]; data[0] = 0; } for(int dat: data) { System.out.println(dat); } } } public static void main(String[] args) { alg(); } } The output: ..\Playground\:10: error: cannot find symbol for(int dat: data) { ^ symbol: variable data location: class myCompression 1 error Thanks for any responses.

8th Feb 2017, 2:09 AM
StaticComs
StaticComs - avatar
3 Answers
+ 4
It's risky speculating (don't want to waste your time), but...if memory serves me right (from Android work) your problem stems from defining "data" within an "if" statement. IOW, there's no guarantee to the compiler that "data" will be there later because it can't know the test will ever succeed. I think the way I was resolving this was to define it outside the "if" (so that it's there, but potentially uninitialized) and assign it inside the "if".
8th Feb 2017, 2:51 AM
Kirk Schafer
Kirk Schafer - avatar
+ 3
The "data" array is not within a reachable scope as it is declared locally and not globally. You have to declared the "data" array outside so that it can be reached and not out of scope
8th Feb 2017, 3:54 AM
Deddy Tandean
+ 2
Your data variable in the if statement is out of scope for the for each loop where the error. You need to declare it somewhere else so that it isn't out of scope.
8th Feb 2017, 2:56 AM
ChaoticDawg
ChaoticDawg - avatar