How to execute a variable outside of the for loop?


#1

I am trying to create a program that will ask the user to enter some results for test#1, #2, etc, and for it to repeat in a for loop until it hits test #4. Then I want the program to find the highest entry and the lowest entry and print what test number it belonged to.

My problem is, if I include the print statements in the loop, it will repeat those statements again four times, when I only want it to conduct once. But if I leave it outside of the loop, the print statement will not know what the variable i is.

I tried creating the new k variable as seen in the code below, but it does not give me the correct output.

Does anyone have any ideas? Thanks!

                                int k = 0;
				for(int i = 1; i<=4; i++){
					//collect blood sugar readings
					System.out.println("Enter the blood sugar test reading for test: "+i);
					bloodSugarReading = input.nextInt();
						k = i;
}

//snip

System.out.println("Test reading "+k+" had the highest blood sugar level with "+highReading+" mg/dL");
System.out.println("Test reading "+k+" had the lowest blood sugar level with "+lowReading+" mg/dL");


#2

In your example above, the k inside the block is shadowing the variable outside of the block. Java defines this as illegal. I can't advise a work around, but it might be a scenario where a method can add more flexibility... parameter in, return value out.


#3

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.