I'm trying to add a Objects to a vector be when I use the Code Pasted below I get errors that says "Syntax error on token(s), misplaced construct(s)." and "Syntax error on token "gamePaddle", VariableDecloratorID Expected after this token." I've looked everywhere and can't find what I'm doing wrong they all tell me to construct the Vector like this. The error happens on the line that starts ListOfGameObjects.add(...
class GameWorld {
/**
* Code that instantiate, hold, and manipulate GameOobjects and related game state data.
* #author Tyler Thomas
*
*/
Paddle gamePaddle = new Paddle();
Ball gameBall = new Ball();
Edge topEdge = new Edge(50, 150);
Edge bottomEdge = new Edge(50, 0);
Edge leftEdge = new Edge(0, 75);
Edge rightEdge = new Edge(100, 75);
Vector<GameObject> ListOfGameObjects = new Vector<GameObject>();
ListOfGameObjects.add(gamePaddle);
}
You're trying to add a statement within a class declaration.
You need to put this inside a code block, e.g. inside a constructor:
class Gameworld {
....
public GameWorld() {
ListOfGameObjects.add(gamePaddle);
}
}
If you do the above, the padde will be added to the ListOfGameObjects when the GameWorld object is constructed.
P.S. you should also probably rename it "listOfGameObjects". The initial capital letter is usually reserved for class names. This is a useful convention that will make your code easier to read / understand.
P.P.S. You should also consider replacing the Vector with ArrayList. Vector is considered a bit outdated nowadays.
Any non-instantiating code, like ListOfGameObjects.add(gamePaddle); needs to be inside a method.
For a simple example like this one, put all your code inside public static void main
Related
short description of what I am trying to do: I'm building a simple game where the user controls a vehicle and after some time more and more ghosts begin following the player, they follow the same trajectory as the player did with a delay.
To accomplish this I create an Array that contains the history of the player's location as a sequence of points. The problem, however, is that when I look at the data stored in this array I see that on all indices only the most recent location is stored.
First I create the array in a botManager class:
public class BotManager {
private ArrayList<Bots> bots;
private List<Point> history;
BotManager() {
history = new ArrayList<>();
bots = new ArrayList<>();
}
Then in the update method of the manager class I add the current location of the player to the array
public void update(Point currLoc) {
history.add(currLoc);
for (Bots bot : bots) {
bot.setLocationData(history);
bot.update();
}
}
A look at the update method in the main GameView class, in case I forgot something here
public void update() {
player.update(playerPoint);
botManager.update(playerPoint);
}
In the bots class' constructor I pass the history list (locationData) and determine its length to find out the delay in positioning. After which the following code handles the position of the bot.
#Override
public void update() {
loc = locationData.get(delay - 1);
this.rectangle = new Rect(loc.x - Constants.BOTSIZE/2, loc.y - Constants.BOTSIZE/2,
loc.x + Constants.BOTSIZE/2, loc.y + Constants.BOTSIZE/2);
}
To get back to the problem, whenever I check the contents of the history array, I find that it only contains one point on all indices, and its the most recent even when I moved the player, causing the ghost to always remain on top of me.
So my question here is, what am I doing wrong here?
Not clear from your posted code, but could it be, that you are just modifying the Point which you are adding instead renewing your object's Point objects?
Try
public void update(Point currLoc) {
history.add(new Point(currLoc)); // new Point object added here
for (Bots bot : bots) {
bot.setLocationData(history);
bot.update();
}
}
So this is my very first mini-javaproject and I have been stuck for days now on the basic structure and the (non existing) relation between anything within my code. I linked the code in my comment below, could not paste it in here for some reason - (Main is empty, so did not copy it.)
So I spent some time getting my head around the basics of Java (as my first programming adventure) and to be honest I felt pretty confident. (On Codewars I completed like 100+ Katas, but of course those are "single-class", so I was not prepared for the "real world.)
It is hard to exactly pinpoint my question, but I will try to give some examples.
1, (Main is empty right now, but anyway) Basically "nothing can be used" in main. Like methods of objects, like room1, or player1, etc.
2, In my Room.java line 21-22 why is the object room1 not visible? Why does Intellij say "Unknown class: RoomArray if I just created that very thing before??
3, I understand that I am supposed to have my variables set to private, which I plan to do later on. Also, I should use setter and getter methods, which I tried to do so with basically everything. But for example in Player.java I have this
Player player1 = new Player(300, 50, "Conan", 75, false);
public Player getPlayer1() {
return player1;
}
and if I try to use the getPlayer1() method in any other class it just simply can not see/access it?
3, And to make me even more confused Room1 class has access to getMyDungeon () method created in the Dungeon class. Why is that so?
(Maybe it has to do with inheritance? The fact that Room1 extends Room which extends Room? But if so, it seems strange because not all classes can have a HAS-A or IS-A relationship with something. An example - if I create all 10 Rooms later on as Room1, Room2, etc. in separate classes, how could I ever create a Room [] array containing them? No matter where I started to do that it will always give me the error "Cannot resolve smybol" for all the Room objects...)
I have spent the past few days reading up on the topic and understand it all, but still when I try to build this project it all falls apart. I realize that an experienced programmer might not even my question because how basic it is, but if anyone can help me to get this whole thing clear in my head, I would appreciate it. (Really not looking for the complete code, but just some direction I should go, or the missing step, etc.)
It seems you to be trying to create an object within the class of that object The correct use is:
public static void main(String[] args){
Player player1 = new Player(300, 50, "Conan", 75, false);
}
or if you want your Room class to have a lot of players
public class Room {
//this object will be create when you do Room room = new Room();
List<Player> players = new ArrayList<>();
public void createPlayer(){
players.add(new Player());
}
//this is a getter
public List<Player> getPlayers() {
return players;
}
}
your Player:
public class Player {
//Fields and Methods
}
and your main:
public static void main(String[] args)
{
Room room =new Room();
room.createPlayer();
for (Player p:room.getPlayers()) {
//p.doSomething
}
}
if you want an object to be created without the need to create an instance from the outside you need to use the static keyword (don't do that unless you know what you are doing)
static Player player1 = new Player(300, 50, "Conan", 75, false);
public static Player getPlayer1() {
return player1;
}
I am making a roguelike based on Trystan's Tutorial and running into issues with implementing a class system. I'm pretty sure the solution is simple, but bear with me.
class Creature {
int HP;
CharacterClass playerClass = new Wizard();
HP = playerClass.hitDie;
ArrayList<Ability> creatureAbilityList = new ArrayList<>();
creatureAbilityList.add(classAbilityList.get(1));
}
class CharacterClass {
int hitDie;
ArrayList<Ability> classAbilityList = new ArrayList<>();
}
class Wizard extends CharacterClass {
Wizard() {
hitDie = 6;
classAbilityList.add(new Ability(magicMissile));
}
}
I'm getting a "Syntax error on token ";", , expected", on the semicolon following "new Wizard()". I'm fairly sure that this isn't the issue however, but instead the way that my classes and inheritance is set up. How should I set up the code instead? Any help would be appreciated.
The problem is the row below. It should be
int HP=playerClass.hitDie;
(and remove the line int HP;)
you should make hitDie private, and make it accessible with getter and setter to enable the polimorphism (and so the getHitDie() invoked will be the one of the class Wizard instead of the one of the class CharacterClass)
Syntax error on token ";", { expected after this token.
I got this error on the 11th line and 19th line. Is there anyone can tell me what's the problem with it?
import java.util.*;
class veding_machine{
State st;
veding_machine vm;
private int price;
private int k;
private int k1;
private int t;
private int s;
State Ls[]=new State[7]; // 11th line
Ls[0]=idle;
Ls[1]=coins_inserted;
Ls[2]=sugar;
LS[3]=nsc;
Ls[4]=nlc;
Ls[5]=et;
Ls[6]=st; // 19th line
public veding_machine(){ k=0; k1=0; t=0; price=0;
}
public void setK(int k){
this.k=k;
}
Initialize that array inside a Constructor, you can't initialize them like that, initialize them when you declare the array, or in a Constructor or in a initialization block. And correct the spelling mistake. Have look on this tutorial.
Ls[0]=idle;
Ls[1]=coins_inserted;
Ls[2]=sugar;
Ls[3]=nsc;
Ls[4]=nlc;
Ls[5]=et;
Ls[6]=st
;
The initialization of Ls should be inside the vending_machine constructor and should be creating instances of the classes "idle" and "coins_inserted", etc...
Ls[0] = new idle();
Ls[1] = new coins_inserted();
Ls[2] = new sugar();
Ls[3] = new nsc();
Ls[4] = new nlc();
Ls[5] = new et();
Ls[6] = new st();
and these classes need to extend the State class
class idle extends State {
// ...
}
They don't need a state instance inside them.
// removed, State st;
public coins_inserted(){
// removed, st=new State();
}
State Ls[]=new State[7]; // 11th line
This is an instantiated array. You should place it in the constructor or initialization block. Also it is better to init the reference in the Java way:
State[] Ls = new State[7];
This
LS[3]=nsc;
should be
Ls[3]=nsc;
And again init those elements in the constructor or init block.
Also, I know this doesn't answer the question but I just have to say something about naming and style. Please name vending_machine class like VendingMachine and give the other objects more descriptive names instead of vague letters. Following convention helps when you come back to your code a week/month/year later and saves you from trying to figure out what the hell you were doing. Even if it is just a little project in school that is where it matters most that you learn and practice these conventions.
Also, it's nice when code is aesthetically pleasing.
Working on a project in school, I'm a beginner to programming and I have big problems with the making of Bubble Shooter, I need to get all of the balls of the map before it changes to map2..
Trying to make it with listing all of the balls but the program crashes at the end of the first map and gives us the error-report that it can't load a negative value. I figured it was when it was trying to load the gun and wanted to put an if-statement that says that if "allowedBallTypes != null" or zero, as it might be, than it should load the gun.
cannot find symbol - getAllowedBallTypes();
greenfoot java method class
The bubbleworld class:
public BubbleWorld()
{
super(Map.MAX_WIDTH*Map.COLUMN_WIDTH, Map.MAX_HEIGHT*Map.ROW_HEIGHT, 1,false);
// Max speed. We use time-based animation so this is purely for smoothness,
// because Greenfoot is plain stupid. I can't find a way to get 60 Hz so this is
// what we have to do. Note: Exporting the game seems to cap this to some value < 100. :(
Greenfoot.setSpeed(100);
// Load the map.
map = new Map(this, testMap1);
// Update the allowed ball types. (i.e. we don't want to spawn a
// certain color of balls if the map doesn't contain them!)
map.updateAllowedBallTypes();
// Create the cannon.
Cannon cannon = new Cannon();
addObject(cannon, getWidth()/2, getHeight());
The map class:
public int[] getAllowedBallTypes()
{
return allowedBallTypes;
}
public void updateAllowedBallTypes()
{
int allowedCount = 0;
boolean[] allowed = new boolean[Ball.typeCount];
// Only ball types that exist in the map RIGHT NOW as attached balls will be allowed.
for(Cell c : cells)
{
if(c != null && c.getBall() != null && c.isAttached())
{
int type = c.getBall().getType();
if(!allowed[type])
allowedCount++;
allowed[type] = true;
}
}
allowedBallTypes = new int[allowedCount];
int writeIndex = 0;
for(int type = 0; type < Ball.typeCount; ++type)
{
if(allowed[type])
{
allowedBallTypes[writeIndex++] = type;
}
}
}
The Cannon class:
private void prepareBall()
{
// Get a random ball type from the list of allowed ones. Only balls currently in the map
// will be in the list.
int[] allowedBallTypes = ((BubbleWorld)getWorld()).getMap().getAllowedBallTypes();
int type = allowedBallTypes[Greenfoot.getRandomNumber(allowedBallTypes.length)];
// Create it and add it to the world.
ball = new Ball(type);
getWorld().addObject(ball, getX(), getY());
}
Assuming you are getting that error in the pasted snippet of the Cannon class, the error suggests that there is a problem with the getMap() method of BubbleWorld -- can you paste that in so we can see it? It might not be returning the correct type. In general, you need to paste in more code, including complete classes, and say exactly where the error occurs. An easier way might be to upload your scenario with source code to the greenfoot website (www.greenfoot.org -- use the share function in Greenfoot, and make sure to tick the source code box) and give a link to that.
Based on your code, your map class doesn't seem to have a class-level variable declaration of int[] allowedBallTypes;