• Log in or sign up for an account here: https://www.sythe.org/login

Need help with declaring variables

I am Indian

Forum Addict
Joined
Mar 9, 2011
Sythe Gold
0
Messages
448
I'm totally new to Java basics. I've had my own RSPS, and I'm good on coding that, but now I want to make something totally by me. I've a shitty problem in declaring variable.

I want to declare a variable, but I don't know how to. I just started with Java 2 days ago in my school and we've just learnt making a calculator.

int n1,n2,r1,q;
n1=Integer.parseInt(cb.getText());
r1=Integer.parseInt(tw.getText());
if (n1 > 10 && n1 < 20) {
n2 = 450;
} else if (n1 > 20 && n1 < 30) {
n2 = 400;
} else if (n1 > 30 && n1 < 40) {
n2 = 350;
}
q=n2*r1; <-- error saying 'variable n2 might have not been initialized'.

I don't have to declare n2 as a text like I declared n1 & r1. Above, I've made n1 declare the value of n2. E.G.
if (n1 = 10) {
n2 = 400;
} else if ...........
In order to remove the error off my 'q=n2*r1;' part, I need to declare n2.

I'm not able to express what I meant I guess, but if you get me, please reply helping me.

Thanks.
 
EDIT: Don't listen to me, I misread what you wrote.
 
In Java, primitive data types (int, char, boolean, etc...) need to be declared and initialized.

A declaration statement is any line of code that includes the data type and the variable name. Data type is the type of variable that it is (int, char, short...).
To initialize a variable is to set its value to something. The reason you are getting an error is that it tries to compare one number (say 10) to a null variable. Null does not mean 0, it means the variable has not yet been initialized.

There are two main types of declaration statements.


Those that include the initialization:

int numStudents = 3;


And those that don't:

int numStudents;


The difference between the two, is that the second does not initialize the variable; it only declares it.
This is acceptable as long as the variable receives a value before being used.

Correct declaration and initialization in 2 lines:

int numStudents;
numStudents = 3;

Hope this helps :)
 
Runescape Gamblingrunescape gambling
Back
Top