I have 10 variables called, int1, int2, int 3 and so on. The user can write one number into the console. If the user types 7, I want to add 3 to the value of int7. how do I do this without 10 if statements? can I somehow do something like, (int + "userinput") += 3? thank you for your help! :D | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

I have 10 variables called, int1, int2, int 3 and so on. The user can write one number into the console. If the user types 7, I want to add 3 to the value of int7. how do I do this without 10 if statements? can I somehow do something like, (int + "userinput") += 3? thank you for your help! :D

31st Jul 2016, 4:45 PM
madnessbox
2 Answers
+ 3
or use array in int variables instead of 10 separate ints and write something like this: array[userNumber - 1] += 3; (if user types in 7, it will direct to the seventh element which has index 6)
31st Jul 2016, 5:01 PM
Tomek Cymes
Tomek Cymes - avatar
+ 3
Either use an array like the last answer suggests or a case statement. Ask yourself what happens if the user enters a number greater than 10. A case statement would ensure that if a user enters a value you are not expecting then the default answer will be the result. You could set the default value to display a message telling the user what they need to type in to output the correct answer. additionally, I'd put the case inside a while loop telling the case statement to execute until the user provides valid input.
31st Jul 2016, 5:49 PM
Mike
Mike - avatar