This week's book giveaway is in the OO, Patterns, UML and Refactoring forum. We're giving away four copies of Refactoring for Software Design Smells: Managing Technical Debt and have Girish Suryanarayana, Ganesh Samarthyam & Tushar Sharma on-line! See this thread for details.
System.out.print("insert the grade of mid1"); input.readLine(); mid1=Integer.parseInt(inputString ); System.out.println("mid1:"+mid1); System.out.print("insert the grade of mid2"); input.readLine(); mid2=Integer.parseInt("inputString"); System.out.println("mid2:"+mid2); System.out.print("insert the grade of final"); input.readLine(); finalex=Integer.parseInt("inputString"); System.out.println("finalex:"+finalex); sum=mid1+mid2+finalex; System.out.print("the average is ") System.out.print("AVE:"+sum/3); } }
when i compile it its write to a comment for (inputString that i didnt initilize it ???
There are a few things that are wrong with your code. 1) You try to use inputString before it is initialised. Amend you code so that inputString has a value 2) You are missing a semi-colon off one of your lines of code 3) You should be catching exceptions but your not
Indeed, you have not initialized inputString. You "initialize" an object by creating an instance of that object. When you write:
You have done nothing more than created a reference called "inputString" which points to nothing. You have not created a String object, just the 'marker' that will be used to refer to the String once you create it.
If instead you write:
You have initialized it. What "initialized" means is that an object's constructor has been called.
Now, some caveats:
The construct I used above is considered bad practice, due to peculuarities of the String class (which I won't explain here, for fear of clouding the issue at hand). I only use it here because it is clear you are constructing a "new" object. Instead, this is the way to initialize a String:
You may also fix this compilation error by assigning inputString to a pre-existing String object instance (and this is particularaly pertinent given what you application seems to be trying to do). You do this like this:
Also, there is one occasion where you can "initialize" an object for use by your reference without actually constructing an object. This is when you assign the value to be null: