I was trying to write a mapper class for a practice program and the compiler always gives me error that: satMath and satVerbal might not have been initialized.
public class UniversityMapper extends Mapper <LongWritable,Text,Text,IntWritable> {
public void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
// TODO convert record (value) to String
StringTokenizer iterator = new StringTokenizer (value.toString(),")" );
int state = 2;
int satVerbal;
int satMath;
while(state != 0 && iterator.hasMoreTokens())
{
String cur = iterator.nextToken();
if (cur.contains("sat verbal"))
{
state--;
StringTokenizer temp = new StringTokenizer(cur,"\\s+");
temp.nextToken();
temp.nextToken();
int satV = (new Integer(temp.nextToken())).intValue();
satVerbal = satV;
//context.write(new Text("satv"), new IntWritable(satVerbal));
}
else if (cur.contains("sat math"))
{
state--;
StringTokenizer temp = new StringTokenizer(cur,"\\s+");
temp.nextToken();
temp.nextToken();
int satM = (new Integer(temp.nextToken())).intValue();
satMath = satM;
//context.write(new Text("satm"), new IntWritable(satMath));
}
}
if (state == 0)
{
System.out.println(satVerbal);
System.out.println(satMath);
context.write(new Text ("satv"), new IntWritable(satVerbal));
context.write(new Text ("satm"), new IntWritable(satMath));
}
} }
If I reposition the context.write() method within the scope of the if statements (commented out in the code) I no longer get this error. I cannot understand why. I usually code in c++ and python I am really new to Java and I need to finish this program. Can somebody help me with this, thanks in advance :)
This is fairly straightforward. If this else if
does't execute:
else if (cur.contains("sat math"))
Then you never initialize satMath
, and you try to access it later via:
context.write(new Text ("satm"), new IntWritable(satMath));
Same goes with if (cur.contains("sat verbal"))
and satVerbal
.
If you wish to avoid these altogether you could just initialize + declare those variables yourself:
int satVerbal = 0;
int satMath = 0;
But you should be absolutely certain that they will be assigned something else inside your while
, otherwise you will actually use their initialized values (0
) later in your context.write
, which I assume isn't desirable for you.