Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of Changing input variables in a java loop without wasting too much if your time.
The question is published on by Tutorial Guruji team.
The question is published on by Tutorial Guruji team.
I have an assignment, and I need to use a loop to allow a user to enter ten different numbers in a programme which then adds up the variables.
I have found various pieces of code and stitched them together to create this:
import javax.swing.*; import java.util.Scanner; public class exercise6 { public static void main (String []args) { //Input String totalNum, num1, num2, num3, num4, num5, num6, num7, num8, num9, num10; Scanner in = new Scanner (System.in); System.out.println("Please enter ten numbers:"); int[] inputs = new int[10]; for (int i = 0; i < inputs.length; ++i) { inputs[i] = in.next(); } //Process totalNum = num1 + num2 + num3 + num4 + num5 + num6 + num7 + num8 + num9 + num10; //Output JOptionPane.showMessageDialog(null, "Total = " + totalNum); } }
It’s not great, but it’s the best I have so far. Please help?
Answer
You don’t need the variables num1 to num10. You can simply sum up in the loop itself. Like:
int sum = 0; for (int i = 0; i < 10; i++) { sum += = in.next(); // sum = sum + in.next(); }
Furthermore you assigned your variables as Strings, but you need int. In your case it would print something like 1111111111, if the input would always be a 1.
Take a look here how you would handle Integers properly.
We are here to answer your question about Changing input variables in a java loop - If you find the proper solution, please don't forgot to share this with your team members.