0

Beginner question

Why can't this programme display result: import java.util.Scanner; public class Program { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int a = scanner.nextInt(); for (int i=a-1;i<=1;i--){ int result= a*i; } System.out.println(result); } }

15th Jun 2018, 8:32 PM
Adam
Adam - avatar
7 Answers
+ 3
I think you should change the bottom limit in your for cycle. Your limit is I <=1 which means the cycle won't stop - an infinite loop. Maybe you mean I>=1.Also the result variable should be declared outside of the for loop.
15th Jun 2018, 8:42 PM
TheWh¡teCat 🇧🇬
TheWh¡teCat 🇧🇬 - avatar
+ 2
You declared the variable result inside the for loop, so it can only be used there. To fix it, put int result before the for loop.
15th Jun 2018, 8:40 PM
Alexandru Turculet
Alexandru Turculet - avatar
+ 1
I'm not great at java, but I think you should do int result = new Int ();
16th Jun 2018, 7:03 PM
Alexandru Turculet
Alexandru Turculet - avatar
0
thanks
15th Jun 2018, 8:51 PM
Adam
Adam - avatar
0
But still if I change the above mentioned things, it says result might not have been initialized. import java.util.Scanner; public class gyak { public static void main(String[] args){ Scanner scanner = new Scanner(System.in); int a = scanner.nextInt(); int result; for (int i=a-1;i>=1;i--){ result= a*i; } System.out.println(result); } }
16th Jun 2018, 6:58 PM
Adam
Adam - avatar
0
That wouldn't be good syntactically, I get the error when I try to print it out.
16th Jun 2018, 7:10 PM
Adam
Adam - avatar
0
I had to set the starting value of result, now it works
16th Jun 2018, 7:13 PM
Adam
Adam - avatar