I am currently building a program where the user inputs up to 1000 numbers (-1000 to indicate the end of input), and a number of equations are to be applied. However I have encountered a problem with the "for loop" in case 1. The variables initialized and modified within the for loop do not persist outside of it. Is there any way to get around this? Or perhaps a method that doesn't require calculations inside of a loop.

Scanner keyboard = new Scanner(System.in);
    	double[] values;
    	values = new double[1000]; //create a 1000 slot array
    	for(int count = 0; count <= values.length; count++){
			values[count]  = keyboard.nextDouble();
			if (values[count] == -1000){
				//start calculations
				System.out.println("1. Mean");
				System.out.println("2. Variance and Standard Deviation");
				System.out.println("3. Histogram");
				System.out.println("4. Exit");
				int switchvar = keyboard.nextInt();
				switch (switchvar){
					case 1:
						System.out.println("Mean: ");
						for(int c = 0; c <= values.length; c++){
							double meantrans = values[c] + values[(c+1)];
						}
						double mean = (meantrans / c);
						String meanstr = mean.toString();
						System.out.println("Mean = " + meanstr);
						break;
					case 2:
						System.out.println("Variance and Standard Deviation");
						break;
					case 3:
						System.out.println("Histogram");
						break;
					case 4:
						return;
						break;
				}

Also, I am new to Java, so try not to use code beyond a beginners scope.

Thanks for walking me through this.
Cheers,

Recommended Answers

All 2 Replies

You have to declare them outside the loop. Read this about scope.

You have to declare them outside the loop. Read this about scope.

Thank you so much for the link. I'll read up on it and see what I can do.

Cheers,

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.