+ 1
Whats wrong with the following code
//it shows some error import java.util.Scanner; public class Program { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); float loan = scanner.nextFloat(); float ret1; float ret2; float ret3; float sumOfReturns; float remain; for (int month = 1; month<=3; month++){ if ( month == 1 ){ ret1 = loan * 1/10; } else if ( month == 2){ ret2 = loan * 1/10; } else if (month == 3){ ret3 = loan * 1/10; } else{ break; } } sumOfReturns = ret1 + ret2 + ret3; remain = loan - sumOfReturns ; System.out.println(remain); } }
5 Réponses
+ 4
When you declare a variable, it just get allocated memory, not Initialize to any value. So if you try to get it's value then it raise error, it is not initilized any value or no value it has.
Ex:
int a, b;
int c = a + b; // what is the values for a, b? Error
So it need to assign a value before you using it..
Ex:
int a=5, b=7;
int c =a+b; //no error.
I said to assign 0 so it does not effect on calculations.. You can set any value but must set a value before you using it.
You are assigning those in loop but it does not guarantee initialzation at compile time. It assigns values at run time. So statement
sumOfReturns = ret1+ret2+ret3; at compile time raise error as unintilzed...
Hope it helps...
+ 3
float ret1=0;
float ret2=0;
float ret3=0;
Initialize it to default, before using it..
your else part has no use.
loan*1 has no effect. instead just use loan/10 or loan*0.1
+ 1
You are a life saver. Thank you.
0
Thanks it did the work. Your tips made it more efficient
Would you bother telling me why do I have to initialize those variables to its default value?
0
🙏🤗
You're welcome..