How important is commenting on the project?
We've all been asked to write code according to the ICS Java Coding Standard. I won't grade against it, but I will need to look into the code, and comments will help me, so I'd appreciate enough commenting to make the code understandable.
What kind of code do I need so that the program know that I am passing a command line argument?
In Java, the only code you need is your public static main
method with String
array arguments.
public class HelloWorld { public static void main(String[] args) { : } }
Java puts the command line arguments into this array automatically. For example, if you compile and run this program from the command line like this:
$ javac HelloWorld.java $ java HelloWorld apple banana coconut 123 456 789
The args array will contain these six string elements:
args[0] ← "apple" args[1] ← "banana" args[2] ← "coconut" args[3] ← "123" args[4] ← "456" args[5] ← "789"
If you've never worked from a command line, you might try glancing through these Wikipedia articles:
http://en.wikipedia.org/wiki/Command-line_interface
http://en.wikipedia.org/wiki/Command-line_argument
How do I use command line arguments in Eclipse?
Here are the steps for how to specify command line arguments in Eclipse.
Go to "Debug" → "Debug Configurations" or "Run" → "Run Configurations".
Go to the second tab, "Arguments", and type your arguments in the "Program arguments" text box.
Click "Apply", and Eclipse will remember your arguments for future run or debug sessions.
In Eclipse, the standard output is displayed in the "Console" tab, as you can see below.
How do I use command line arguments in jGRASP?
Here are the steps for how to specify command line arguments in jGRASP.
Go to "Build" → "Run Arguments".
A tool bar appears in which you can specify the arguments.
Click "Run" or "Debug". In jGRASP, the standard output is displayed in the "Run I/O" tab, as you can see below.
I'm not too sure if my program is what the professor wanted. Could you please check my code and let me know if it's right.
I'm not supposed to review, correct, or pre-grade students' code via email before the due date, but if you'd like to bring your work to our labs, or come see me during my office hours, I'd be very happy to go through it with you.
Can we bring our own laptops to the lab?
Yes, you can bring and work on your own computer. POST provides WiFi.
Would it be possible to provide, beforehand, example input and output for the assignments? This is what we came to expect for our assignments in ICS 111.
I agree that one of the first things we need to know about an assignment is the expected input and output. This information is covered in the assignment description, and we also try to discuss this in our labs.
If you can't attend the labs, you might want to check out the example test reports for the Fall 2008 ICS 211 class, which are available online. Even though the assignments aren't going to be identical, these reports should give you a pretty good idea of the expected input and output of the programs.
http://www.jade-cheng.com/uh/ta/ics-211-fall-2008/#assignments
As always, if you think something is unclear about the assignment description, please bring it to the attention of the professor or me, and we'll do our best to clarify things.
What do you type to get the NoSuchElementException
error?
You have to close the standard input stream. An easy way to do this from the command line is by typing Control-C while your program is waiting for standard input.
I'm using Eclipse. How do we use the command line argument to pass a file?
In general, when running your program from the command line, it's easiest to put the file you want to open in the current (working) directory. For example,
# ls file.txt YourProgram.class # java YourProgram file.txt :
To set the current directory in Eclipse, you can go to "Debug" / "Debug Configurations" or "Run" / "Run Configurations"; select the second tab, "Arguments", for your configuration; and set a value for the "Working directory." By default, this value will be the root workspace location of your project, which is next to the "src" folder in the "Package Explorer" view.
Then, in your code, you need something like what I wrote on the board. You would use something like File
or FileReader
together with Scanner
to obtain lines from your file. Like this:
: try { File file = new File(args[0]); Scanner scanner = new Scanner(file); while (scanner.hasNextLine()) { String line = scanner.nextLine(); : } } catch(FileNotFoundException e) {...} :
For assignment 1, it says "prints the number of non-vowel strings at the end of the loop." Does that count the space (" ") we put into the beginning of the new array?
Yes, you count the space at index 0 as a non-vowel.
For assignment 1, is "y" considered a vowel?
No, "y" is not considered a vowel in this assignment. "a", "e", "i", "o", and "u" are vowels.
For assignment 1, does the program need to print the number of non-vowel strings at the end of EACH loop or the LAST loop?
The program should print the number of non-vowels only once.
For assignment 1, should the program ask only once for the user input or keep going until the user enters a number like -1 to stop the program from asking and goes on to printing the new array?
The program should ask only once, and it should display an error and terminate if the user enters anything other than a valid integer.
For assignment 2, should I print 1?
No, the number 1 is not considered a prime number.
For assignment 2, When you want us to analyze the big-O runtime of our program, how would you like us to word it?
Basically, you need to identify the big-O time complexity for your program and provide a brief explanation of how you came to this conclusion. You may include these as a block of comments at the end of your code.
For assignment 2, I'm not sure on how to do the runtime analysis.
There are different ways to get started.
For assignment 2, Regarding the big-O, what is the big-O of the following piece of code (from textbook P113)? Is it 2n
?
for (int k = 0; k < n; k++) { statement1 statement2 }
We're looking for the big-O complexity, so you don't need to count every statement of your code. For the example above, since O(k*n) = k*O(n)
, where k
is a constant, it doesn't matter how many elementary operations occur in the loop; the entire block of code is just O(n)
. If one of the statements is not an elementary operation, such as a recursive method call, then the complexity will change.
For assignment 2, Regarding the big-O, Is the "*" counted as one statement in the following piece of code?
static void printPrime(int x, int y) { if (x == y) { s.o.pln(y); // statement1 } else if (x % y != 0) { printPrime(x, y+1); // * : } : }
It's a statement but it's not one elementary operation. Therefore this statement must be considered when determining the run-time complexity since it's a recursive method call based on the input size.
For assignment 3, is DirectoryFullException
a method or a class? And what does it mean that DirectoryFullException
extends Exception
?
DirectoryFullException
is a class that extends the Exception
class. This is an example of the concept of Inheritance.
http://en.wikipedia.org/wiki/Inheritance_(object-oriented_programming)
In Java, exceptions are objects. When you throw an exception, you throw an object. This object must descend from Throwable
. Throwable
serves as the base class for an entire family of classes declared in java.lang
. Throwable
has two direct subclasses, Exception
and Error
.
To create your own exception class, you need to declare it as a subclass of some member of the Throwable
family. In general, the Throwable
classes you define should extend class Exception
, and this is what the assignment asks us to do.
In the diagram above the boxes represent classes, and the arrows represent inheritance (extend). The Java syntax for extending a base class looks something like this:
: class BaseClass { ... } class DerivedClass extends BaseClass { ... } :
For assignment 3, how are we taking input? Via scanner/Joptionpane or commandline arguments?
By reading standard input.
For assignment 3, do we need to prompt the user to provide a phone number alongside with the name?
No, you don't need to ask for any numbers. Every bit of user input is treated as a string.
For assignment 3, the Directory
class must also provide a method String toString()
, which provides a readable version of the contents of the telephone directory. Is that what we use to print?
Yes, you would print the contents of the directory by calling:
: System.out.println(yourDirctory.toString()); :
For assignment 4, what are the exact steps of pushing and poping for different characters?
The exact steps are described in detail in the assignment description. Here I'll use an example to show this procedure. For example, let's say we want to calculate "8 - 2 * 3 + 5".
Evaluating the operand '8', push it onto the operand stack:
Evaluating the operator '-', since the operator stack is empty, push it onto the operator stack:
Evaluating the operand '2', push it onto the operand stack:
Evaluating the operator '*', since '*' has a higher precedence than '-', push it onto the operator stack:
Evaluating the operand '3', push it onto the operand stack:
Evaluating the operator '+', since '+' has a lower precedence than '*', pop, compute, and push the computed result onto the operand stack. Since '+' has an equal precedence to '-', pop, compute, and push the computed result onto the operand stack again. Now, since the operator stack is empty, push '+' onto the operator stack:
Evaluating the operand '5', push it onto the operand stack:
At this point, all tokens have been read from the expression, so pop and compute the remaining items in the stacks. Once there are no items remaining in the operator stack, there should be one and only one item remaining in the operand stack, which is the answer, 7.
For assignment 4, how can I take a character from the text file one by one?
You would first obtain a line as a String
from the file using String line = scanner.nextLine()
. Then, you would loop through this line and evaluate each character. The length of the line can be retrieved by calling int length = line.length()
. Each character of the line can be retrieved by calling char ch = line.charAt(index)
.
For assignment 4, we need one stack of array for the digits and one stack of array for the operators, right?
Yes, you need two stacks, which you may implement using arrays.
For assignment 4, as in the StringArrayStack.java
example, would my stack constructor look like this?
public StringArrayStack() { top = 1; array1 = new String[?]; array2 = new String[?]; }
No. You would declare two stack objects, and each of them would contain one array of strings (in your example).
For assignment 4, can we decide any size for the array in the stack class?.
If you use an array to implement your stack, you'll need to define a maximum size for the stack. Just make it large enough to compute lines at least as long as the professor's example input file.
For assignment 4, when the array is full, should we make a new array double in size as the textbook example does?.
You may, but that's not necessary. If your stack is full, you may display an error and terminate the program gracefully. I'm not going to test if your program handles extremely long lines.
For assignment 4, when I run my code, it gives me Java heap space error.
That's caused by allocating too many bytes in the heap (with a "new"). For example the following the code would produce that error:
public class JavaHeapError { public static void main(String[] args) { int[] x = new int[1000000000]; } }
For assignment 5, are the acceptable inputs "save" and "quit" case sensitive?
They should at least work for lower cases like they were written on the assignment description, but you could easily make them case insensitive by using:
: if (userInput.equalsToIgnoreCase("save")) {...} if (userInput.equalsToIgnoreCase("quit")) {...} :
For assignment 5, in the main method if an invalid entry is entered, does the program repeat asking for input until a valid entry is obtained or should the program exit as an error?
There won't be any invalid user input because everything other than "quit", "save", and strings containing '@' are treated as names. For names, your program should attempt to remove the corresponding entries. If no such entries exist, your program should report this condition and prompt the user for another command.
For assignment 5, does the main method repeat until the "quit" input option is entered or after one input entry is entered?
It should repeat until the user types "quit".
For assignment 5, what is a path, and how can we use it outside of main()
?
A path is a string that uniquely identifies a file on your computer. For example, "C:\Windows\system32\cmd.exe" is the path to the command prompt program in Windows. In your main()
, the first item of the args array will indicate the path to the file you will open and read into the linked list. You should pass this string to the Directory
(LinkedList
) constructor as a parameter.
For assignment 5, I'm using generics, and when I call node.getData().getName()
, I get,
LinkedList.java:xx: cannot find symbol
symbol : method getName()
location: class java.lang.Object
It's likely your getData()
method is not returning a type that you defined. The Java compiler can't find the getName()
method anywhere in the inheritance hierarchy, all the way up to java.lang.Object
.
You need to have something like this:
class Program { public static void main(String[] args) { Node<Data> node = new Node<Data>(); : String fieldOne = node.getData().getFieldOne(); float fieldTwo = node.getData().getFieldTwo(); int fieldThere = node.getData().getFieldThere(); : } : } class Node<T> { private T data; : public T getData() { return data; } : } class Data { private String fieldOne; private float fieldTwo; private int fieldThree; : public String getFieldOne() { return fieldOne; } public float getFieldTwo() { return fieldTwo; } public int getFieldThree() { return fieldThree; } : }
For assignment 5, how can I read three lines at a time?
If you can read one line, it should be easy to read three. For example, in pseudocode:
while ( <scanner has next line> ) { String line1 = <read one line>; String line2 = <read one line>; String line3 = <read one line>; : }
For assignment 5, how do I compare strings in the nodes?
The String
class has comparison methods, which you should use to compare strings. Do not write your own string comparison method.
For assignment 5, when I print my nodes I get,
Node@1b67f74
Node@69b332
Node@173a10f
From your output, it seems like the default toString
was printed. By default, it prints the object type and its memory address, and that what you are seeing there.
You might want to provide a toString
method for your Node
class and have this method return a printable version of the node's data. If you need to print your linked list, then make a toString
method for the linked list class, have it loop through each node, and then return a printable version of the list.
For assignment 6, how many classes should I have?
It depends on your implementation. If you are doing the linked list collection way, you might have three classes, YourNode<T>
, YourLinkedList<T>
, and YourLinkedListIterator<T>
. If you are doing the array collection way, you might have two classes, YourArray<T>
and YourArrayIterator<T>
. You may or may not create a class dedicated to the main
method.
For assignment 6, I still don't understand what the add
and iterator
methods from collection do?
The add
method will add an object into the collection. For example, if you have a collection that contains {2, 4, 1}, and you pass 8 to the add
method, your collection would become {2, 4, 1, 8}.
Your iterator
method must return an object (that you create) that implements the Iterator<T>
interface. This object allows a consumer to loop over the contents of your collection. For example,
Iterator<String> i = yourCollection.iterator(); while (i.hasNext()) System.out.println(i.next());
For assignment 6, I'am trying to make a generic array, but i get an error when creating a generic array like this, T[] array = new T[1000];
?
This is a commonly asked question about Java generics. Java does not support the creation of arrays of generic type arguments (T). Most people seem to implement this with the following code,
@SuppressWarnings("unchecked") T[] array = (T[]) new Object[1000].
But you'll see this generates a warning. If you like you could also implement this by passing a pre-created array to the collection class constructor.
class YourCollection<T> { private T[] array; public YourCollection(T[] paramArray) { this.array = paramArray; } : } : YourCollection<String> collection = new YourCollection<String>(new String[1000]); :
For assignment 7, what happens when the user's command is "null"? Should it be allowed, or denied? Should I do queue.offer("")
.
When the user enters "null", your program would attempt to offer by calling queue.offer(null)
. That would be rejected because our offer
method doesn't accept null
values.
For assignment 7, how do I make both classes work for my main method? I have the following code, and it keeps telling me to change the variable name queue
for the ArrayQueue
.
public static void main(String[] args) { LinkedListQueue queue = new LinkedListQueue(); ArrayQueue queue = new ArrayQueue(); : }
Of course we can't have two variables with the same name in the same scope. Just comment out one of the two as you test the other one and vice versa. For example, you could leave your code like this:
public static void main(String[] args) { //LinkedListQueue queue = new LinkedListQueue(); ArrayQueue queue = new ArrayQueue(); : }
or this:
public static void main(String[] args) { LinkedListQueue queue = new LinkedListQueue(); //ArrayQueue queue = new ArrayQueue(); : }
I'll test the disabled queue by uncommenting it and commenting the enabled queue.
For assignment 8, for the Taxpayer
, what is used as comparable value - name, SSN or the amount of tax.
The SSN is used as the key value for comparisons of Taxpayers
.
For assignment 8, for displaying the database, should it be JOption pane or just console?
The console is fine.
For assignment 8, which files should I modify?
As stated in the assignment description, you need to add the findNext
and findPrevious
methods, and you need to modify the toString
method in the BinarySearchTree
class. Then, in order to present these features to the user, you will need to modify the IRSMenu
class accordingly. Before submitting your assignment, you need to change IRSMenu
to LastNameFirstName8
.
For assignment 8, I don't know what exactly the user is suppose to be able to do with this program.
The code that the professor provided allows the user to manipulate a binary search tree database. The already existing operations include populating a database from the CSV file, adding and removing entries from the database, and displaying the database in the console window. Your job is to provide the user two more operations on the database, find next and find previous. You also need to modify the toString
method of the binary search tree class so that it displays the contents of the database as a tree (see below).
For example, consider the following binary search tree:
The values returned by the findNext
and findPrevious
methods are listed below.
key value
findNext
findPrevious
2 5 none 5 8 2 8 10 5 10 15 8 15 20 10 20 23 15 23 25 20 25 27 23 27 30 25 30 40 27 40 45 30 45 none 40
The toString
output of the database is shown below. If you tilt your head to the left 90 degrees, you will see the tree: the root node is at the top, and the leaves are at the bottom.
45 40 30 27 25 23 20 15 10 8 5 2
For assignment 10, what kind of heap are we creating?
We are constructing a binary min heap, which will be used to implement a qriority queue. The following diagram demonstrate an example:
For assignment 10, how do the parent children indexes related with each other?
Let's use the binary min heap above as an example. Since our heap is implemented using a fix size array, the elements above will be stored as:
The parent-children relationship in the array is:
So we have the following:
index/role parent left child right child 0 none 1 2 1 0 3 4 2 0 5 6 3 1 7 8 4 1 9 10 5 2 11 none 6 2 none none 7 3 none none 8 3 none none 9 4 none none 10 4 none none 11 5 none none
By observing the patern, we learn that,
parentIndex = n
leftChildeIndex = 2n + 1
rightChildIndex = 2n + 2
For assignment 11, how is the comparator used in the program?
The picture of your program looks something like,
LinkedList<T> { : public void sort(Comparator<T> c) {...} : } YourStringComparator implements Comparator<String> { : public int compare (String s1, String s2) {...} : } YourTestMainClass { public static void main(String[] agrs) { LinkedList<String> list = new LinkedList<String>(); list.add("jade"); list.add("edo"); : Comparator<String> c = new YourStringComparator(); list.sort(c); : } }
For assignment 12, how does increasing the array size help when a collision occurs if we're using the String.hashCode
method to compute the hash for a given name regardless of the array size?
For instance, we have the following strings, an aray of size 7, and a hash method %:
string: "jade" "ics" "edo" hash code: 3254264 104089 100272 hash mod: 6 6 4
As we see there is a collision because "jade" and "ics" hash into one place. Now we increase the size of the array to 15,
string: "jade" "ics" "edo" hash code: 3254264 104089 100272 hash mod: 14 4 12
Now we resolved the collision by increasing the size of uor hash table.