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 .
Related
I have two classses and I wonder why I always get an error when I try to create an object of class "Knoten" in a method of class "Graph".
Class Graph
public class Graph
{
static Knoten[] knotenliste;
public void punktHinzufuegen(int x, int y){
for(int i=0;i<Gui.zaehler;i++){
knotenliste[i]=new Knoten(x,y);
}
}
}
Class Knoten:
public class Knoten{
int xPos;
int yPos;
public Knoten(int x,int y){
xPos=x;
yPos=y;
}
}
Every time I call method punktHinzufuegen I get an error. Thanks for helping..
Your problem is a very easy problem to solve, so I'll give a short explanation/solution.
What your current problem is, is that you are not defining your knotenliste.
You should define it as the following field:
private static Knoten[] knotenliste = new Knoten[Gui.zaehler];
I would suggest that you do not use a static value but start working with either a fixed ArrayList (in order to index your graph points) or a Queue. Both of those can be found on the Java documentation if you're intested in reading about them.
What I would have done is the following:
public class Graph {
private final ArrayList<Knoten> knotenliste = new ArrayList<>(Gui.zaehler);
public void punktHinzufuegen(int x, int y) {
for (int i = 0; i < Gui.zaehler; i++) {
// Keep in mind that the List#add(int index, E element) will
// shift all the elements previously in the array to the right.
knotenliste.add(i, new Knoten(x, y));
}
}
}
With this you do not only stop abusing the static keyword, but you also have a more flexible Collection to save your Knoten in.
You haven't initialized your array and I think you are getting NullPointerException while adding elements. You need to initialize it before adding elements to it
static Knoten[] knotenliste = new Knoten[<SOME_INT_VALUE>];
So, I'm trying to practice my java skills by applying it to some math homework and making a frequency distribution chart using inheritance. In my head, I envision it as a frequency distribution (parent class = FreqDist) that can have multiple "MyStatClasses" (in the form of the MyStatClass array). Each FreqDist has variables that span across all MyStatClasses which is why I put them in the parent class. However, when I call the MyStatClass constructor, my program gets a StackOverflowError. I think this is because the super(s, i) line calls back to the FreqDist constructor and starts over, causing an infinite loop. Assuming this is the case, how would I fix this?
Ideally, I'd like to access my MyStatClass array and grab values that only apply to that MyStatClass, but I cannot get it to work.
public class FreqDist {
private MyStatClass[] freqClasses;
private double[] dblValuesArray;
private int intNumberOfClasses;
private double dblMax;
private double dblMin;
private int intClassWidth;
public FreqDist(String strValues, int intNumOfClasses) {
System.out.println("This is the beginning of the FreqDist constructor...");
dblValuesArray = getDoubleValues(strValues);
intNumberOfClasses = intNumOfClasses;
dblMin = dblValuesArray[0];
dblMax = dblValuesArray[dblValuesArray.length - 1];
intClassWidth = (int)Math.ceil((dblMax - dblMin) / intNumberOfClasses);
freqClasses = new MyStatClass[intNumberOfClasses];
for (int x = 0; x < freqClasses.length; x++) {
freqClasses[x] = new MyStatClass(strValues, intNumOfClasses);
}
}
public double[] getDoubleValues(String strValues) {
String[] strValuesArray = strValues.trim().split(" ");
dblValuesArray = new double[strValuesArray.length];
for (int x = 0; x < strValuesArray.length; x++) {
dblValuesArray[x] = Double.parseDouble(strValuesArray[x]);
}
Arrays.sort(dblValuesArray);
return dblValuesArray;
}
public int getNumberOfClasses() {
return intNumberOfClasses;
}
public double getMin() {
return dblMin;
}
public double getMax() {
return dblMax;
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("What are the values? ");
String values = scan.nextLine();
System.out.print("How many classes? ");
int classes = scan.nextInt();
FreqDist fd = new FreqDist(values, classes);
}
}
public class MyStatClass extends FreqDist {
public MyStatClass(String s, int i) {
super(s, i);
}
}
Ok so this is mostly an issue with a flaw in your design.
From what I understand FreqDist is a class that should contain an array of MyStatClass. You want them to have the same properties so you make MyStatClass extend FreqDist. However when you call FreqDist it MyStatClass which Calls a new MyStatClass over and over and over.
One way to solve this is to create a new class that has the shared properties you want FreqDist and MyStatClass to have, and have those two classes inherit from said class. Then create separate constructors for FreqDist and MyStatClass.
A parent type should never refer to its own subtypes, as yours does. Her the parent initializes subtype instances, which require that each initialize the parent type, which initializes subtype instances, which initialize their parent type, which initializes... KABLOOEY!
I had to create this point program a year ago, a year ago it worked fine. Now I have to revisit it and upon compiling and trying to run it I ran into the error of the fact that an abstract class cannot be instantiated. I have done some looking around online and figured out that some update or sort with Java has made it where the method of using PointClass point1 = new PointClass(); is no longer valid and will through an error.
I have yet to find an answer for fixing the error when trying to instantiate the class using a driver program. I also saw that in order to use an abstract class now, a subclass must be present. The thing is is that due to the instructions of the program I cannot use a subclass. Only the driver and the point class.
The program is very simple, just declare some points and call them from the abstract class in order to print to the screen. I need some help on figuring out the updated method to make this work again without the instantiated error.
The PointClass
public abstract class PointClass {
private int pointX;
private int pointY;
//set instance variables
public PointClass() { this.pointX = 10; this.pointY = 10; }
public PointClass(int x, int y){ this.pointX = x; this.pointY = y; }
//make getters and setters
public void setPointX(int x) { this.pointX = x; }
public void setPointY(int y) { this.pointY = y; }
public int getPointX() { return this.pointX; }
public int getPointY() { return this.pointY; }
//make string for format with driver
public String toString() { return "x = " + this.pointX + " y = " + this.pointY; }
}
The Driver
public class PointTest {
public static void main(String[] args){
System.out.println();
PointClass point1 = new PointClass(); //set point1 as no argument
PointClass point2 = new PointClass(11, 24); // set point2 as argument with x and y
System.out.println("Point1: " + point1); //display point1 from toString method
System.out.println();
System.out.println("Point2: " + point2); //display point2 from toString method
System.out.println("---------------------");
}
}
The best thing to do would be to remove the abstract keyword. There's no need for it. Point has no abstract methods.
If you can't do that for whatever reason, you can create inline anonymous classes by adding curly braces after each instantiation:
PointClass point1 = new PointClass() { };
PointClass point2 = new PointClass(11, 24) { };
By the way, your claim that this used to work is incorrect. It has never been possible to directly instantiate an abstract class. That is in fact the entire point of the keyword, to prevent a class from being instantiated.
I'm having a problem with my Java assignment on inheritance. I won't go into detail on the task as that's not my issue. In the program. have a superclass with some fields in it. Two of these fields are ints, xCoord and yCoord. There is then a subclass that obviously also has these ints. It also has another attribute, short direction, that is not contained in the superclass. I need to access all three of these attributes in the user class. The user class needs to be able to change these values. When attempting to compile. I get the error:
error: ';' expected
in all the lines in my user class that try to increment xCoord or yCoord. For example:
mov1.yCoord++
^
So, I don't really know what the problem is. I assume it has something to do with the attributes not be directly declared in that class. My reasoning for this is because I have lines that deal with the short direction in the same manner. For example:
mov1.direction = 1
This goes through the compiler with no problem. So I reckon in must be because xCoord and yCoord only declared in the super class. But that's just my assumption, I could be wrong. Regardless if whether I am or not, I need to fix this while still using inheritance for these fields, the assignment requires it. Any help?
For reference, here are some snippets of relevant code:
The superclass: (didn't include the methods because not relevant)
public class StationaryThing {
// Attributes
protected String name;
protected final int gridlength = 10;
protected final int gridwidth = 10;
public int xCoord;
public int yCoord;
// Constructor
public StationaryThing(String name, int xCoord, int yCoord) {
this.name = name;
this.xCoord = xCoord;
this.yCoord = yCoord;
}
The subclass: (again, didn't include methods)
public class MovingThing extends StationaryThing {
// Attributes
public short direction = 0;
// Constructor
public MovingThing(String name, int xCoord, int yCoord) {
super(name, xCoord, yCoord);
}
And some of the relevant lines from the user class:
for (int i = 0; i < noMoves; i++) {
if (mov1.direction == 0) {
if (hole1.xCoord == mov1.xCoord && hole1.yCoord == mov1.yCoord+1) {
mov1.direction = 1;
mov1.holeAhead();
mov1.directionChange();
}
if (mov1.yCoord == 9) {
mov1.direction = 1;
mov1.directionchange();
}
else {
mov1.displayAttributes
mov1.yCoord++;
}
}
Again, thanks for any help you can give.
Are those lines "missing ;" inside a method? There cannot be "just code" inside the class, but there should be a method like
public void doSth () {
a++;
}
Please refer java code is showing error. ( ';',expected) for a similar situation.
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.