Consider the following image:
Assuming the Person
class exists and has a constructor that takes name
and age
as arguments, write the
appropriate lines of code to create the correct variables and objects that match what you see pictured above. Your code does not need to be inside of
a method or a class.
Consider a file containing words separated by spaces. The number of words per line is not fixed. You may assume that all lines will contain at least one word. Here are the contents of an example file, words.txt
:
land spiders apparatus sweltering
thoughtless
modern wax colour
crack alike level smooth
Write the public method wordSearch
which operates as follows:
/**
* Search the given file for the specified word.
*
* @param word The word to search for.
* @param filename The filename of the file to be searched
* @return true if the word is in the file and false otherwise
*/
Consider the following examples:
wordSearch("land", "words.txt")
returns true
wordSearch("gorilla", "words.txt")
returns false
wordSearch("like", "words.txt")
returns false
wordSearch("colour", "words.txt")
returns true
Consider the following buggy code that raises an exception when executed:
public class DoubleBoxReturns {
private double[] arr;
private int numDoubles;
public DoubleBoxReturns() {
double[] arr = new double[10];
int numDoubles = 0;
}
public boolean append(double val) {
if (this.numDoubles < this.arr.length) {
this.arr[this.numDoubles++] = val;
return true;
}
return false;
}
public static void main(String[] args) {
DoubleBoxReturns db = new DoubleBoxReturns();
db.append(1.0);
}
}
When executed, this code raises the following exception:
Exception in thread "main" java.lang.NullPointerException
at DoubleBoxReturns.append(DoubleBoxReturns.java:11)
at DoubleBoxReturns.main(DoubleBoxReturns.java:20)
A. Identify and describe the bug that is causing the exception.
B. Rewrite the buggy code so that it functions properly.