- May 9, 2005
- 2,044
- 1
- 81
I'm new to programming in general, but I am currently enrolled in intro to Java and need some help with my homework! We are working on "An introduction to object-oriented programming". I need help with #1 and #3 in this lab. Any help would be greatly appreciated!
1. Let's cheat! This program is identical to the sample program of the lesson. Your job is to insert a single line of code where indicated to FORCE the value of dice d1 to be the same as the value of dice d2. HINT: Remember cascading (you can code a call anywhere the returned data type makes sense).
3. The Java "newbie" that wrote this didn't know about information hiding. The application uses the Dice class of the lesson and is supposed to FORCE the value of the Dice object to be its highest possible value after it is rolled. As written, the program won't compile. See if you can fix it by changing ONLY the code inside the application class.
1. Let's cheat! This program is identical to the sample program of the lesson. Your job is to insert a single line of code where indicated to FORCE the value of dice d1 to be the same as the value of dice d2. HINT: Remember cascading (you can code a call anywhere the returned data type makes sense).
Code:
public class Lab17A {
public static void main(String[] args) {
Dice d1 = new Dice();
Dice d2 = new Dice();
System.out.println("Start: " + d1.getValue() + ", " + d2.getValue());
do {
d1.roll();
d2.roll();
// YOUR STATEMENT GOES HERE
System.out.println("Rolled: " + d1.getValue() + ", " + d2.getValue());
} while(d1.getValue() != d2.getValue());
System.out.println("Game over");
}
}
class Dice {
private int sides;
private int value;
public Dice() {
setSides(6);
roll();
}
public void setSides(int n) {
if (n >= 2)
sides = n;
else
sides = 6;
}
public void setValue(int n) {
if (n > 0 && n <= sides)
value = n;
}
public int getSides() {
return sides;
}
public int getValue() {
return value;
}
public void roll() {
value = (((int)(Math.random() * 1000)) % sides) + 1;
}
}
3. The Java "newbie" that wrote this didn't know about information hiding. The application uses the Dice class of the lesson and is supposed to FORCE the value of the Dice object to be its highest possible value after it is rolled. As written, the program won't compile. See if you can fix it by changing ONLY the code inside the application class.
Code:
public class Lab17C {
public static void main(String[] args) {
Dice d = new Dice();
d.roll();
d.value = d.sides;
System.out.println("Value: " + d.value);
}
}
class Dice {
private int sides;
private int value;
public Dice() {
setSides(6);
roll();
}
public void setSides(int n) {
if (n >= 2)
sides = n;
else
sides = 6;
}
public void setValue(int n) {
if (n > 0 && n <= sides)
value = n;
}
public int getSides() {
return sides;
}
public int getValue() {
return value;
}
public void roll() {
value = (((int)(Math.random() * 1000)) % sides) + 1;
}
}
