...for my coursework which is due in tomorrow! I have a variable scope problem which I'm not sure how to resolve.
Okay I have code that looks like this (simplified, assume it's within a 'main' function, which is inside a class with the same name as the file)
Code:
if (args.length != 2) {
System.out.println("bugger off");
return;
}
else {
String mode = args[0];
String sequence = args[1]; // for clearer variable names
}
if (mode="herring") {
doSomethingUsefulWith(sequence);
}
Okay so it tells me it can't resolve 'mode' or 'sequence'. I think I understand why... I declared them within the else-clause, right?
So I suppose I could fix this by declaring them (but not setting values) at the top, before the argument checking bit, then within the else-clause I just set their values?
Well, fair enough, though I dislike the idea that I have to declare variables at the top that, depending on the argument checking bit, might not get used (indeed NOTHING further will happen unless there are just the two arguments that are required). Any alternative? Can I do it my way but stick some smart keyword in when 'mode' and 'sequence' are defined, some word that means 'KEEP MEEEE!'?
My second problem is similar but can't be resolved the same way, how can I resolve it at all? I have a HashMap. The keys are chars, but depending on what the first argument to the program is, the values need to be either integers or strings. So after the argument-number-checking bit, the code looks like this... (the game's up, it's a bioinformatics course)
Code:
String aaSet = "ACDEFGHIKLMNOPQRSTUVWY";
if (mode.equals("-count")) {
HashMap<Character, Integer> residues = new HashMap<Character, Integer>(22);
for (int i=0; i<22; i++) {
residues.put(aaSet.charAt(i), 0);
}
}
else {
HashMap<Character, String> residues = new HashMap<Character, String>(22);
String aaCodes = "AlaCysAspGluPheGlyHisIleLysLeuMetAsnPylProGlnArgSerThrSecValTrpTyr";
for (int i=0; i<22; i++) {
residues.put(aaSet.charAt(i), aaCodes.substring(i*3,(i+1)*3));
}
}
// now run through each letter of the input sequence
for (int i=0; i<sequence.length(); i++) {
char res = sequence.charAt(i);
if (residues.containsKey(res)) {
// oh no you naughty boy, I don't know what the variable 'residues' means because I r dumb.
}
}
As far as I can see I can't declare the residues HashMap outside the if-else blocks as I don't yet know what type the values in the hash will be.
Haalp.