Applied
6.1 Activity: Spot the bug
The code provided opposite doesn't conform to any kind of coding standards. Furthermore, it contains a bug, and doesn't do what it's supposed to do! At the moment, it's almost impossible to determine where the bug might be and how to fix it.
In your groups, fix up the code so that it meets the FIT9131 Coding Standards (see Lesson 3.4). As well as fixing up the spacing and line breaks, make sure each variable and method is given a meaningful name that helps describe what the program is supposed to be doing.
Identify and fix the bug in the code. Was it a syntax, runtime, or logic error? Was it difficult to find once the code had been cleaned up?
After Fix
import java.util.Scanner;
public class BuggyClass
{
private String name;
public BuggyClass()
{
name = "No one";
}
public BuggyClass(String msg)
{
name = msg;
}
public static void main(String[] args)
{
BuggyClass buggyClass = new BuggyClass();
buggyClass.welcome();
}
public void welcome()
{
Scanner console = new Scanner(System.in);
System.out.println("Please enter your name");
String input = console.nextLine();
if (input.trim().length()>0)
{
name = input;
}
System.out.println("Welcome " + name);
}
}6.2 Activity: Buggy Collections
The code given opposite does the following:
- Asks the user to enter a list of integers (as many as they like), typing -1 to finish the sequence.
- Stores the integers in an ArrayList.
- Gives the user the option to remove one of the integers they entered from the ArrayList, using one of three methods,
removeNum1,removeNum2, orremoveNum3.
However, the code contains bugs. In your groups:
- Find and correct the syntax error. Hint: you may need to check the syntax of a method in the Iterator class.
- Run the program and try each method, in turn. Enter at least 5 numbers with -1 as the last number. Select a number to remove. Check the output. Does the method work? If not, was it a runtime or logic error. Identify the bug by stepping through the code carefully, work out exactly what is happening in each case, and where/how the error is occurring.
- Decide which of the three methods should be used to perform the task, and fix the bug in that method.