reset password
Author Message
cysun
Posts: 2935
Posted 15:03 Apr 22, 2011 |

I'm grading Lab 1 and can't help but notice how tedious some of the code is. For example:

while ((line = br.readLine()) != null){
                count++;
                switch (count){
                case 0:
                    break;
                case 1:
                    q = new String(line);
                    break;
                case 2:
                    a = new String(line);
                    break;
                case 3:
                    b = new String(line);
                    break;
                case 4:
                    c = new String(line);
                    break;
                case 5:
                    ans = Integer.parseInt(line);
                    break;
                default:
                    count = -1;
                    entries.add(new TestEntry(q,a,b,c,ans));
                    break;
                }
                size++;
            }
}

could simply be

while( (line = br.readLine()) != null )
{
  // skip empty lines
  if( line.trim().length() == 0 ) continue;

  // a test entry always consists of five lines
  entries.add( new TestEntry(line, br.readLine(), br.readLine(), br.readLine(), Integer.parseInt(br.readLine()) );
}

and

return (userAnswer == correctAnswer ? true : false);

could be

return useranswer == correctAnswer;

and

public boolean isLastEntry() {
    if (currentTestEntryIndex == entries.size() - 1)
        lastEntry = true;
    else
        lastEntry = false;
    return lastEntry;
}

could be

return currentTestEntryIndex == entries.size() - 1;

Remember that by writing concise code you will

  • type less and be more productive
  • reduce the possibility of errors and debug less code
  • make your code more readable


 

Last edited by cysun at 15:05 Apr 22, 2011.