QuickQuiz002.v2
Download
Report
Transcript QuickQuiz002.v2
Object-Oriented Software Engineering
CS288
UniS
1
UniS
2
import java.awt.*;
import java.awt.geom.*;
public class StringArt {
public static void main(String[] args) {
Frame f = new ApplicationFrame("StringArt v1.0") {
private int mNumberOfLines = 25;
private Color[ ] mColors = { Color.red, Color.green, Color.blue };
public void paint(Graphics g) {
Graphics2D g2 = (Graphics2D)g;
Dimension d = getSize();
for (int i = 0; i < mNumberOfLines; i++) {
double ratio = (double)i / (double)mNumberOfLines;
Line2D line = new Line2D.Double(0, ratio * d.height,
ratio * d.width, d.height);
g2.setPaint(mColors[i % mColors.length]);
g2.draw(line);
}
}
};
f.setSize(200, 200);
f.setVisible(true);
}
}
UniS
3
Quick Quiz
• Strings can be joined together with "+", e.g.
"this string" + "that string" = "this stringthat string", note no space.
Also note null+"any string" = "nullanystring", which is undesirable in output.
• Change the SimpleClass to include a new method, stringOfAllValues (has
same type as getUselessField ). When called this method returns a string
which contains all the strings given to uselessField by setUselessField joined
together as a single string. E.g. if uselessField has had values "a", "b", and "c"
so far then stringOfAllValues will return "abc". (Note: this will require adding a
new field, and watch out for null strings!)
(10 marks)
UniS
Recall class is of this form:
public class SimpleClass {
private String uselessField;
public SimpleClass(String newFieldVal) {
setUselessField(newFieldVal);
}
public void setUselessField (String newUselessField) {
uselessField = newUselessField;
}
/* then more code */
4
}
Solution (Additional Code to Simple Class)
private String allValsJoined =""; (4 marks),
2 for new field,
2 for setting it to ""
(4 marks, 2 for correct statement, 2 for putting it at end)
public void setUselessField(String newUselessField) {
uselessField = newUselessField;
allValsJoined = allValsJoined + uselessField;
}
public String stringOfAllValues ( ) {
return allValsJoined;
(2 marks:
}
correct declaration and syntax)
UniS
5