Last modification: 03/10/2016
In the util
package create an IntVector
class, which represents a sequence of integers.
Add an array of integers as private field.
Write a constructor which takes an array of integers as argument. Take care to not expose the internal state.
Write an add()
method, which adds an integer argument to every element in the sequence.
Write a toString()
method as well, which returns the elements in the sequence as a string. The elements should be separated with a whitespace. For instance [1 2 3]
.
Create a Calculator
program, which takes a sequence of integers and a constant integer as arguments. The program adds the constant to every element in the sequence and prints the result. For instance:
$ java Calculator 1,2,3 5
[6 7 8]
Make use of the above util.IntVector
class.
Modify your util.IntVector
class so that it uses a java.util.LinkedList<A>
instead of an array to store the integers.
Little help on how to use a java.util.LinkedList<A>
.
xs.add(elem)
adds elem
to the end of xs
.xs.get(i)
gets the i
th element of xs
.xs.set(i, elem)
overwrites the i
th element of xs
with elem
.xs.size()
returns the size (length) of xs
.Simplify the Calculator
class by using java.util.Scanner
.
The most important methods of java.util.Scanner
here are nextInt()
and hasNextInt()
.
Improve your util.IntVector.toString()
method by using the StringBuilder
class.