Generating Random instances of subclasses using a Abstract Superclass - java

So I have been busting my head over this program assignment and I have no idea how do finish it. I have already completed 80% of it but the last part I don't know even the general idea. The question is
"Then write a method randomVehicle that randomly generates Vehicle references, with an equal probability for constructing cars and trucks, with random positions. Call it 10 times and draw all of them."
I have a main method, an Abstract Superclass Vehicle and two subclasses of Car and Truck. I know how to do probability using loops but I have no idea how to take that probability answer (1 will be truck and 2 will be car) and use it to reference the predefine shapes of the car and and truck.
In other words, how would I create the program that after I hit compile and run, will make these randomly decided car and truck and display it.
Sorry if the question is confusing but I am just learning about abstract classes.
Here is the code thus far:
Main Method
import java.awt.*;
#SuppressWarnings("serial")
class drawTest extends Canvas{
public drawTest(){
setSize(800, 600);
setBackground(Color.white);
}
public static void main(String[] argS){
drawTest canvas = new drawTest();
Frame aFrame = new Frame();
aFrame.setSize(800, 600);
aFrame.add(canvas);
aFrame.setVisible(true);
}
public void paint(Graphics canvas){
Vehicle car = new CarTest();
car.paint(canvas);
paint(canvas);
}
}
CarTest Class
import java.awt.*;
#SuppressWarnings("serial")
public class CarTest extends Vehicle{
public void paint(Graphics canvas){
canvas.drawOval(10+super.x, 30+super.y, 15, 15); // Front Wheel
canvas.drawOval(45+super.x, 30+super.y, 15, 15); // Back Wheel
canvas.drawRect(5+super.x, 10+super.y, 60, 20); // Bottom of Car
canvas.drawRect(15+super.x, 5+super.y, 40, 5); // Bottom of Car
}
}
TructTest Class
import java.awt.*;
#SuppressWarnings("serial")
public class TruckTest extends Vehicle{
public void paint(Graphics canvas){
canvas.drawRect(30+super.x, 5+super.y, 100, 30); // Cargo Section
canvas.drawOval(30+super.x, 35+super.y, 15, 15); // Wheel Under Cargo
canvas.drawOval(45+super.x, 35+super.y, 15, 15); // Wheel Under Cargo
canvas.drawOval(100+super.x, 35+super.y, 15, 15); // Wheel Under Cargo
canvas.drawOval(115+super.x, 35+super.y, 15, 15); // Wheel Under Cargo
canvas.drawRect(5+super.x, 15+super.y, 20, 20); // Driver Section
canvas.drawOval(5+super.x, 35+super.y, 15, 15); // Wheel Under Driver
}
}
Abstract Vehicle Class
import javax.swing.*;
import java.awt.*;
#SuppressWarnings("serial")
public abstract class Vehicle extends JApplet{
public Vehicle(){
// Generates Random position
x = (int)(Math.random()*700);
y = (int)(Math.random()*550);
}
public abstract void paint(Graphics canvas);
public void randomVehicle(){
int carTruckChoice = (int)(1+Math.random()*2);
if (carTruckChoice == 1){
// don't know if this is the right implementation
}
else if (carTruckChoice == 2){
// don't know if this is the right implementation
}
}
public int x;
public int y;
}

Pseudocode to get you started:
randomVehicle =
randomPosition = randomPosition()
randomNumber = randomOneOrTwo()
if (randomNumber is 1)
vehicle = new Car()
else
vehicle = new Truck()
vehicle.setPosition(randomPosition)
return vehicle
for 1..10
randomVehicle().draw()
You'd have an abstract class Vehicle, and two concrete subclasses Car and Truck.

public void randomVehicle() {
Random random = new Random();
Vehicle vehicle;
for(int i = 0; i<10; i++) {
int randomChoice = random.nextInt(2);
if(randomChoice == 1){
vehicle = new Car();
} else {
vehicle = new Truck();
}
//draw vehicle here .. vehicle.draw();
}
}

Generally, StackOverflow does not accept homework questions, but I'll make an exception since this is basically an idiom, and since I take it on good faith that you've already tried this.
Here is a method that generates one random vehicle:
public static Vehicle randomVehicle(){
return (Math.random() < .5) ? new CarTest() : new TruckTest();
}
Explanation:
Math.random() generates a number between 0 and 1.
The expression in parentheses tests if it is less than one-half; i.e. it randomly chooses between true and false.
The question mark is the Java ternary operator. If the expression in parentheses returns true, vehicle is initialized to the first operand, i.e. a new instance of Car(), and vice versa for false.

If you want to generate random instances of A subclass then you need 2 things .
1) a data structure holding all "n" instance classes
2) a random distribution of equal probability of landing on any number from 0 to n-1.
The data structure can be implemented using any linear data structure in java ( a list , array , or enum) which holds classes. Then, by iterating through 100 random number generations, you can use reflection to generate instances of your class by directly accessing the class from your array (or enum, or list, etc) based on the index.
The advantage of this solution is that, as you add new car types, you need only to add the class name to the array structure... With no other changes to the underlying implementation.

Related

Syntax error on "x", VariableDeclaratorld expected after this

class anyName
{
int Tcol = 0;
int fc = 0;
int x = 0;
float randx = (random(1, 1000));
float randy = (random (0, 600));
int Tsizes = 1;
{
if (fc >= x) { //Random Ellipse 3
stroke (Tcol);
fill (Tcol);
ellipse (randx, randy, Tsizes, Tsizes);
}
}
}
anyName ranx1 = new anyName();
ranx1.x = 100;
Hi, I am trying to add a class/object to my code and it is not working. This is the class I have so far, but when I instantiate one object from that class (ranx1), and then try change one of the variables inside it (x), it says there is a error. Is there anything I need to change? I would really appreciate any help.
Since I instantiated an object from that class, how would I change the variables for the new object? For example, if in the class x = 0, then I made a copy and this time I want x to = 100, but all the other variables such as Tcol and fc to stay the same. I know this is possible because my teacher taught it, but it is not working right now for me.
ranx1.x = 100;
You need to declare your variables as "public" if you are trying to access from a class that is not in the same package.
I guess your problem is you are trying to access to that attribute from a class that is in another package, you should declare the atrributes as public to gain access to them. But this solution wouldn't be totally correct, a better approach is declaring them as private and creating public getters and setters to access/modify them.
Said that, you should post a working example, that piece code does not compile because you are trying to execute code that is out of any class... and I'm not sure what you are trying to do with the curly braces before the if clause.
when you careate a class, every member has a control access.
when you don't state the control access like:
public x;
protected fc;
private Tcol;
they all get default private.
you can't access private members from outside the class.
do:
class anyName
{
public int Tcol = 0;
public int fc = 0;
public int x = 0;
public float randx = (random(1, 1000));
public float randy = (random (0, 600));
public int Tsizes = 1;
{
if (fc >= x) { //Random Ellipse 3
stroke (Tcol);
fill (Tcol);
ellipse (randx, randy, Tsizes, Tsizes);
}
}
}
whoever, i must point out that most times it's not recommended to set members access as public and you should learn about getter and setters.
now i hope the rest of your code is in a main function and in a main class, but if not it should be like so:
public class Main
{
public static void main(String[]args){
anyName ranx1 = new anyName();
ranx1.x = 100;
}
}
First of all you cannot access sub class veriables like that. If you want to access you should make this
public class ExampleApp {
class anyName
{
int x = 0;
}
public static void main(String[]args){
ExampleApp ea = new ExampleApp();
ExampleApp.anyName ranx1= ea.new anyName();
ranx1.x =100;
}
}
Or you can use them inside of the class with method
public void method() {
anyName ea = new anyName();
ea.x=100;
}
you cannot use your veriables private if you want to access them.Secondly if you want to use this libraries you cant use innerclass. Inside of innerclass you cannot access libraries because java sees it in diffrent package. If you make it public class and import Math you can use it otherwise you should make method for your ellipse, random .

Why can't Java resolve the variable in this for each loop?

In the following for each loop, I get a "bird cannot be resolved" error at lines marked !. I have setup an interface Bird implemented by an abstract class BirdType of which Cardinal, Hummingbird, Bluebird, and Vulture are children. getColor() and getPosition() methods are defined in the abstract class while fly() is unique to each of the child classes. This client code was actually provided by my professor to test the interface/inheritance relations I have setup. Note I have tested the interface, abstract class and child classes and they all seem to work. I think the issue is with the for-each loop but I can provide code for the other classes if needs be. Any advice?
import java.awt.*;
public class Aviary {
public static final int SIZE = 20;
public static final int PIXELS = 10;
public static void main(String[] args){
//create drawing panel
DrawingPanel panel = new DrawingPanel(SIZE*PIXELS,SIZE*PIXELS);
//create pen
Graphics g = panel.getGraphics();
//create some birds
Bird[] birds = {new Cardinal(7,4), new Cardinal(3,8),
new Hummingbird(2,9), new Hummingbird(16,11),
new Bluebird(4,15), new Bluebird(8,1),
new Vulture(3,2), new Vulture(18,14)};
while (true){
//clear screen
g.setColor(Color.WHITE);
g.fillRect(0, 0, SIZE*PIXELS, SIZE*PIXELS);
//tell birds to fly and redraw birds
for (Bird bird : birds)
bird.fly();
! g.setColor(bird.getColor());
! Point pos = bird.getPosition();
g.fillOval((int)pos.getX()*PIXELS, (int)pos.getY()*PIXELS,
PIXELS, PIXELS);
panel.sleep(500);
}
}
}
You need to wrap the body you want to be executed in the for loop in braces
for (Bird bird : birds) {
bird.fly();
g.setColor(bird.getColor());
Point pos = bird.getPosition();
g.fillOval((int)pos.getX()*PIXELS, (int)pos.getY()*PIXELS,
PIXELS, PIXELS);
panel.sleep(500);
}
Otherwise, the body of the for loop is the next statement following the ). So it is equivalent to
for (Bird bird : birds)
bird.fly();
// bird is not in scope anymore
g.setColor(bird.getColor());
Point pos = bird.getPosition();
g.fillOval((int)pos.getX()*PIXELS, (int)pos.getY()*PIXELS,
PIXELS, PIXELS);
panel.sleep(500);
As Darien has said in the comments, indentation is not part of the Java language, it has no bearing on the syntax. But you should use it to make your code easier to read, as expressed in the Java code style conventions.

Creating weapon classes and a Combat Class

I am creating a text based game and I am having some issues.. This is what I have so far. So far I have a Combat Class, and two Classes for two different Weapons. I am trying to assign hit points to the weapons themselves. But my biggest issue is in the Combat class. I am trying to create it to were there will be random weapon drops at random times and also random Weapons. So far in the Combat class I have this:
public class Combat {
final int chanceOfDrop = 3;
static Weapons[] wepArray = {new M4(), new M16()}
static boolean[] hasWeapon = {false, true};
public static int ranNumberGen(int chanceOfDrop) {
return (int) (Math.random()*1);
}
private void enemyDead() {
boolean canDrop = false;
if(ranNumberGen(chanceOfDrop)==0){
canDrop = true;
}
if(canDrop == true){
givePlayerWeapon(Weapon[Combat.ranNumberGen(Weapons.length)]);
}
private static void givePlayerWeapon(int w) {
hasWeapon[w] = true;
for w <(Weapons.length-1) {
if has weapon[w] {
System.out.println(wepArray[w].getWeaponName);
}
}
}
}
}
}
I have issues when I am creating the new M4(), and the new M16() it says Type mismatch: cannot convert form M4 to Weapons. I do have a class named Weapons, could that be the problem?
And here is my M4 Class, both M4 and M16 Classes are identical
public abstract class M4 {
private Integer weaponDamage = 5;
private Integer weaponAmmo = 25;
private String weaponName = "M4";
public M4(String name, int ammo, int damage) {
name = weaponName;
ammo = weaponAmmo;
damage = weaponDamage;
}
public String getWeaponName() {
return weaponName;
}
public Integer getAmmo() {
return weaponAmmo;
}
public Integer getDamage() {
return weaponDamage;
}
}
I don't think I have any issues here. Maybe my problem lies within this though. Although, I have a Weapons class, but nothing in it. Do I need that?
A few things to fix at first sight:
Create a generic Weapon class that defines some properties that apply to each weapon, like name, damage, ammo, scope multiplier, etc... Then create subclasses for Weapon, like M4 and M16, that specify the properties and eventually add weapon-specific properties.
Add brackets to this line:
System.out.println(wepArray[w].getWeaponName); // Change to getWeaponName()
Remove the abstract keyword from M4.
Fix the ranNumberGen method because it will always return 0 right now. Math.random() returns a float in the range [0,1[. This means that casting it to an int will always result in 0. Multiply it by n to have a random int in the range of [0, n[. You probably want this:
public static int ranNumberGen(int max) {
return (int) (Math.random() * max);
}
Change this line:
givePlayerWeapon(Weapon[Combat.ranNumberGen(Weapons.length)]);
to:
givePlayerWeapon(wepArray[Combat.ranNumberGen(wepArray.length)]);
The syntax of a for-loop is like this:
for (variable-initialization; condition; increment)
So in your case, you want:
for (int i = 0; i < hasWeapon.length; ++i)
{
if (hasWeapon[i]) System.out.println(wepArray[i].getWeaponName());
}
You might want to revisit your decision to use an inheritance-style heirarchy for game objects before it is too late.
In practice, I've found a component-entity model and/or prototype model to be much more effective. You could take a look at the code in my old Java roguelike game Tyrant for inspiration:
Weapon definitions: mikera/tyrant/Weapon.java (Github is down right now so can't find the exact link, but should be easy enough to Google)
The idea is that you make your objects by setting properties / composing compoenents in a Map-like game object rather than using static inheritance.
When you want to create a random weapon in this model, you can just get a list of all the possible weapon prototypes, and clone one of them at random to make a new weapon.
the mean of abstract in "public abstract class M4" is that you cannot make a new object with this class.
So you can put all commons fields of your weapons in the weapon class and make m4 and m16 extends the weapon and you code would compile.

Java Constructors or new class

Hey I am new java so forgive me if what I am about to ask is obvious, but I will try to explain as best as I can.
Its just a project that has been set for university so its not in a serious manner.
I have a class called MarsRoom which holds the attributes say for all the dimensions of the room like the totalheight and width of the walls in order to calculate the heat loss that the room will suffer in order to adjust the amount of solar energy that is needed to keep the room at the room temperature set.
The problem I am having is what is better practice or solution, to pass the attributes of the size of the room in a constructor(but this could get quite long in size, as the ones below are not only the ones that I may need) or create a whole different class specifically for that room like ROOM TYPE U? and set the attributes in there.
As it stands I can create a whole new room just by instantiating the room with the new values, but its going to get a little long, whereas I would rather not create a whole new class for a different room which may only differ from another room by a few meters on one of the walls!.
So what I am really trying to get at it, is is it ok to pass that many attributes to the constructor on instantiation?
//the instantiation in the runnable
MarsRoom room1 = new MarsRoom("RoomU", 40, 40, 20, 20, 8, 2, 4);
//the constructor in the MarsRoom class
public MarsRoom(String roomname, int windowsH, int windowsW, int wallsH, int wallsW, int windowC, int heaters, int lights){
name = roomname;
TotalWindowHeight = windowsH;
TotalWindowWidth = windowsW;
TotalWallHeight = wallsH;
TotalWallWidth = wallsW;
windowCeiling = windowC;
numheaters = heaters;
numlights = lights;
roomheaters = new Heaters[numheaters];
}
I'd say that you should be adding factory methods here.
Basically, keep your constructor, but add methods like
static Room createLaundryRoom(laundryRoomParameters) {
return new Room(...laundry room parameters plus defaults
common to all laundry rooms...);
}
One of the great benefits object oriented programming is the possibility of not repeating yourself in code. Hence objects, which define data (members) and functionality (methods), and no requirement to create instances of these "prototypes" with hard values until run-time. To create a new class for each room when it
may only differ from another room by a few meters on one of the walls
would be to deny OOP (and Java) by gross repetition. I'd stick with the constructors, and if similar kinds of rooms end up emerging, try one of the static factory methods suggested, or break up common functionality using inheritanceOracle.
Create a map with the keys being
Map<String, Integer> map = new HashMap();
map.put("TotalWindowHeight", new Integer(10));
map.put("TotalWindowWidth", new Integer(5));
...
map.put("NumberOfHeaters", new Integer(3));
MarsRoom room1 = new MarsRoom("RoomU", map);
Constructor will be like:
public MarsRoom(String roomname, HashMap<String, Integer> params) {
name = roomname;
TotalWindowHeight = map.get("TotalWindowHeight").intValue();
TotalWindowWidth = map.get("TotalWindowWidth").intValue;
...
roomheaters = new Heaters[map.get("NumberOfHeaters").intValue()];
}
this is not good OO however, but it seems like you are looking for something quick. If you want good OO you need to create an object for Window and in it you have hieght and width, another for ceiling, and you should not have number of something as a field, you should have an array to store the heater objects, and so and so forth, but this is quick and meets your requirement.
While technically legal, constructors with very long argument lists may be inconvenient to use. It also depends on whether you this the list may grow in the future or in subclasses.
If you have many parameters, but they have defaults and sometimes only a few need to be changed, you may find the Builder pattern useful. The idea is to replace constructor arguments with function calls, and allow them to be chained, for example:
public MarsRoom() {
//empty or just basic stuff set here
}
public MarsRoom setTotalWindowHeight(int TotalWindowHeight) {
this.TotalWindowHeight = TotalWindowHeight;
return this;
}
public MarsRoom setTotalWindowWidth(int TotalWindowWidth) {
this.TotalWindowWidth = TotalWindowWidth;
return this;
}
...
then, you can call:
MarsRoom room1 = new MarsRoom()
.setTotalWindowHeight(20)
.setTotalWindowWidth(40);
Of course, if you wanted to set all parameters this way, it's longer (thou maybe more readable) than the single constructor. But if you only set 2 parameters out of 10, it will usually be more convenient.
You don't show what the fields of MarsRoom are, but for each feature, I would have a Collection of sub-objects. A MarsRoom has-a List of Windows. A MarsRoom has-a List of Walls. etc... Then have setters and getters for each and methods to add new instances of these features.
Since this is for school, I'm only including a little bit of pseudo code.
public class MarsWindow {
int height;
int length;
// Setters & Getters
// standard getters & setters go here
int getArea() {
return this.height * this.width;
}
}
public class MarsRoom {
List<MarsWindow> windows;
List<MarsWall> walls;
List<MarsLight> lights;
List<MarsHeater> heaters;
public List<MarsWindow> addWindow(MarsWindow window) {
// Add a window to the "windows" list here
}
public List<MarsWall> addWall(MarsWall wall) {
// Add a wall to the "walls" list here
}
// Do this for the other fields
int getTotalWindowArea() {
int area = 0;
// Iterate over all windows
for(MarsWindow window : windows) {
area += window.getArea();
}
return area;
}
// Add other calculation methods here
}
If what you're trying to do is simply not duplicate the parameters you're passing the constructor, you can simply put them in a separate static method, like so:
public static MarsRoom newRoomU() {
return new MarsRoom("RoomU", 40, 40, 20, 20, 8, 2, 4);
}
You could also use some polymorphism or have different types of rooms or something similar to this and then have a superclass with the common values that all rooms will have.
You can also have more than one constructor and have different ones for values you wish to set depending on the room type etc.
Its always better to work with objects rather than primitives, you could use factory to create objects.
//the constructor in the MarsRoom class
public MarsRoom(String roomname, WindowDimension windowDimension, WallsDimensions wallDimension, RoomAmbience ambience){
}
public class WindowDimension{
private int height; //int windowsH
private int width; //int windowsW
private int circumference; //assumed windowC is circumference
}
public class WallsDimension{
private int height; //int wallsH
private int width; //int wallsW
}
public class RoomAmbience{
private int heaters;
private int lights;
}

Combining shape objects to create a composite

i have a program i have to do where i have to take individual shape objects and combine them to create a final car shape. we are given premade shapes such as front tire, back tire, body, windshield, and roof and supposed to combine them into one car shape. the code already given to me is the following:
CompositeShape shape = new CompositeShape();
final double WIDTH = 60;
Rectangle2D.Double body
= new Rectangle2D.Double(0, WIDTH / 6,
WIDTH, WIDTH / 6);
Ellipse2D.Double frontTire
= new Ellipse2D.Double(WIDTH / 6, WIDTH / 3,
WIDTH / 6, WIDTH / 6);
Ellipse2D.Double rearTire
= new Ellipse2D.Double(WIDTH * 2 / 3, WIDTH / 3,
WIDTH / 6, WIDTH / 6);
shape.add(body);
shape.add(frontTire);
shape.add(rearTire);
now, i have to create the compositeShape class which is where the combining takes place, but im not sure what to do in the add(Shape) method. we were also told that we were supposed to use a pathiterator method, but we werent really taught about pathiterator or what we are supposed to do with it. Im not asking for someone to tell me what exactly to code, just some helpful starter points.
the first thing that came to my mind was something like this:
public class CompositeShape implements Shape {
Graphics2D g2;
public void add(Shape shape){
g2.draw(shape);
}
but it doesnt work because i cant instantiate a new graphics object and i get a null pointer exception. after that, im pretty much stumped as to what to do. any help would be greatly appreciated. thanks!
Probably, instead of drawing the Shape inside the add() method, you're just supposed to store the added Shape for drawing later. You could do that by giving CompositeShape some kind of collection to hold Shapes that are added, and that's all I'd put in the add() method. Beyond that, it would depend what other behavior CompositeShape is supposed to have. If you have to be able to draw a CompositeShape, then you'll probably be given an Graphics object to draw on. You won't have to create your own. Then drawing a CompositeShape would be drawing all of the Shapes that it contains.
java.awt.geom.Area can combine multiple shapes with methods add, subtract, exclusiveOr, and intersect. It's a ready-made class for CompositeShape.
It seems extremely weird that you've been asked to recreate it as "CompositeShape", because Area already does what you want.
The solution could be as simple as
class CompositeShape extends java.awt.geom.Area {}
and you're done.
Or, the fact that you've been given a hint about PathIterator, it might be that you're being encouraged to manage the added shapes in a list manually, then implement all the methods of the Shape interface in terms of iterating over the other shapes.
E.g., getBounds() needs to return the rectangular bounds of the shape, so get the rectangular bounds of the first, then use Rectangle.union to join it with the bounds of the others.
And for getPathIterator(), return a new inner class implementing PathIterator that will iterate over all the shapes in your collection, and iterate the path segments of each of their getPathIterator methods, returning each path segment.
It all sounds unnecessary in practice, since the needed class already exists. I think you should get clarification on what is wanted. Good luck.
To clarify what I said about the implementation of getPathIterator, return something like this. I didn't test this. This assumes your list is called shapes.
public PathIterator getPathIterator(final AffineTransform at, final double flatness) {
return new PathIterator() {
private PathIterator currentPathIterator;
private Iterator<Shape> shapeIterator = shapes.iterator();
{ nextShape(); }
private void nextShape() {
if (shapeIterator.hasNext()) {
currentPathIterator = shapeIterator.next().getPathIterator(at, flatness);
} else {
currentPathIterator = null;
}
}
public int getWindingRule() {
return WIND_NON_ZERO;
}
public boolean isDone() {
for (;;) {
if (currentPathIterator == null) return true;
if (!currentPathIterator.isDone()) return false;
nextShape();
}
}
public void next() {
currentPathIterator.next();
}
public int currentSegment(float[] coords) {
return currentPathIterator.currentSegment(coords);
}
public int currentSegment(double[] coords) {
return currentPathIterator.currentSegment(coords);
}
};
}

Categories