There's definitely a way to make a for loop out of variables. So if this button I made is clicked, the program will parse the ints in the textfields and send them to variables num1-num5

if (e.getSource() == calc)
		{
				num1 = Integer.parseInt(num1field.getText());
				num2 = Integer.parseInt(num2field.getText());
				num3 = Integer.parseInt(num3field.getText());
				num4 = Integer.parseInt(num4field.getText());
				num5 = Integer.parseInt(num5field.getText());
				sum = num1 + num2 + num3 + num4 + num5;
				avg = sum / 5;
				ans = "";

				ans = Integer.toString(avg);

				answerfield.setText(ans);

			}

I'm trying to turn the sum statement into a for loop that produces the same result. How do I go about doing this?

I want to know if it's possible. I'm a java noob, so I'm curious to see if you can make a for loop out of something that isn't strictly (i=0; i.length < 5; i++) or something like that. You get the gist.

well, you can put a loop in there, but it wouldn't make your code more efficiƫnt imho, it would just show you know how to use a loop.

you can't really loop over the reading of the numbers, because they're not from the same source (different input fields) and you can not dynamically 'build' the names of the inputfields.

what you could do is read the int's into an array, and loop over that array to add the numbers into sum.

O alright, I got what you're saying. Good idea. Like you said, it'd be pointless to expend the effort to change a functioning code, but now I know how I could go about doing it if need be. Thanks

This question has already been answered. Start a new discussion instead.