Reputation: 49
I am having heartburn with understanding java's variable scoping. Particularly with variables that are scoped for the entire class and being used in methods inside that class, yet not being able to retain their values after leaving the method. I don't get the point.
If I scope a variable inside a method, I expect it to not be available outside the method. But scoped in a class, used in a method in that class, and still the variable's value is *not accessible outside the method? After 6 hours trying to figure out less than 40 lines of code, it's got to be something obvious, but I'm clearly not smart enough... What concept am I not understanding about scope in java?
package myExperimentTests;
import myExperiment.DataUtilities;
public class MyExperimentTests {
public static String num = "2223334444";
public static String ocn = "4134";
public static String company = "This and That, Inc.";
public static long iterations = 1000000;
public static long startTime, stopTime;
public static long accumalatedTime;
public static void main(String[] args) {
DataUtilities utils = new DataUtilities();
for (int i=0; i<iterations; i++){
startTime = System.currentTimeMillis();
utils.IsPhoneNumberChar(num.toCharArray(), 10, 10);
stopTime = System.currentTimeMillis();
accumalatedTime += stopTime - startTime;
}
System.out.println("Evaluating " + num + " as array of char 1Mil times: " + accumalatedTime/iterations);
for (int i=0; i<iterations; i++){
startTime = System.currentTimeMillis();
utils.IsPhoneNumberString(num, 10, 10);
stopTime = System.currentTimeMillis();
accumalatedTime += stopTime - startTime;
}
System.out.println("Evaluating " + num + " as string 1Mil times: " + accumalatedTime/iterations);
}
}
I'm not sure why i'm being asked to explain why a beginner would know the suggested answer would be the same as the answer to this. My inexperience led me to believe this was a variable scope problem, not a datatype/division problem.
Upvotes: 0
Views: 105
Reputation: 942
The problem is related to data types. Long / float / division, etc.
System.out.println("Evaluating " + num + " as array of char 1Mil times: " + (float)accumalatedTime/(float)iterations);
Also, a small debugging tip:
print the value of each var (and/or use a debugger) and not just the calculation e.g.
System.out.println("accumulatedTime " + accumalatedTime);
System.out.println("iters " + iterations);
System.out.println("Evaluating " + num + " as array of char 1Mil times: " + (float)accumalatedTime/(float)iterations);
Upvotes: 1