Unable to increment variable (object oriented programming) - java

I'm stuck on Task2 where i have to increment the counter of enemyships each time an enemy is created. I have created the enemey ships already and made the counter field static (i'm suppose to call the counter number)
The final solution should increment the counter of number enemyships which i need to declare a static field, the field should start at 0, when the first enemyship is created should increment this field to 1, second increment to 2 and so on, then you can use the value of this feild when printing the first line of output. that is for the first enemy, you should print "Enemy #1" second enemy should print "Enemy #2" and so on.
So this is what I tried from my Enemyship class:
public class EnemyShip
{
private int position;
private int velocity;
private int life;
private static int number = 0;
private boolean justHit;
public EnemyShip()
{
System.out.println("Enemy #1");
System.out.print("- Initial position: ");
position = Global.keyboard.nextInt();
System.out.print("- Initial velocity: ");
velocity = Global.keyboard.nextInt();
}
}
i made the public void increment method and tried to use this to increment but it didn't work. wondering if someone could help me explain how i can fix this problem and how to increment a variable in java.
thanks
public class Game {
private PlayerShip player;
private EnemyShip enemy1;
private EnemyShip enemy2;
private EnemyShip enemy3;
public Game() {
player = new PlayerShip();
enemy1 = new EnemyShip();
enemy2 = new EnemyShip();
enemy3 = new EnemyShip();
}
}

From the information you have provided, I understand you have to increment the value of counter everytime an enemy ship is created. So every time you call the constructor you should increment counter.So your increment function should look like this:
public void increment()
{
number = number + 1;
System.out.println("Enemy " + number + "#");
}

Why do you need an increment() method and why do you increment by 3 every time?
The number variable is static so you have access to it anywhere inside your class.
Use it and increment it in the Constructor.
public EnemyShip()
{
System.out.print("- Initial position: ");
position = Global.keyboard.nextInt();
System.out.print("- Initial velocity: ");
velocity = Global.keyboard.nextInt();
life = 10;
boolean justHit = false;
number++;
System.out.println("Enemy #" + number);
}
Every time you call
new EnemyShip();
you will see the statement
Enemy #[some number]
If you want to remember which EnemyShip has which number, you can add an instance field.
private int shipNumber;
public EnemyShip()
{
System.out.print("- Initial position: ");
position = Global.keyboard.nextInt();
System.out.print("- Initial velocity: ");
velocity = Global.keyboard.nextInt();
life = 10;
boolean justHit = false;
shipNumber = ++number;
System.out.println("Enemy #" + shipNumber);
}
This solution is dangerous in a multithreaded environment. I still don't know what your increment() method is for.
EDIT
You seem to be all over the place, lacking some bacis java knowledge of how classes work.
Read this and all of these.
Then run this code
public class EnemyShip {
private static int number = 0;
public EnemyShip() {
number++;
System.out.println("Enemy #" + number);
}
public static void main(String[] args) {
new EnemyShip();
new EnemyShip();
new EnemyShip();
}
}
It will output
Enemy #1
Enemy #2
Enemy #3

OP, you need to call the increment method from somewhere. The method won't run unless you call the method.
public class Game {
private PlayerShip player;
private EnemyShip enemy1;
private EnemyShip enemy2;
private EnemyShip enemy3;
public Game() {
player = new PlayerShip();
enemy1 = new EnemyShip(); EnemyShip.increment();
enemy2 = new EnemyShip(); EnemyShip.increment();
enemy3 = new EnemyShip(); EnemyShip.increment();
}
}
Should do better for you.

Related

How do I access a record from another procedure?

So I am having an issue where I would like to create a record in one procedure, then alter the attributes of that record using other procedures and functions.
import java.util.Scanner; // Imports scanner utility
import java.util.Random;
import java.lang.Math;
class alienPet
{
public void main (String[] param)
{
// We want to call all of the functions
// and procedures to make an interactive
// alien program for the user.
welcomeMessage();
alienCreation();
System.exit(0);
} // END main
/* ***************************************
* Define a method to obtain the users input
* and start the correct method.
*/
public static String userInput (String message)
{
Scanner scan = new Scanner(System.in);
String inp;
print(message);
inp = scan.nextLine();
return inp;
} // END userInput
/* ***************************************
* Define a method to print messages.
*/
public static void print (String message)
{
System.out.println(message);
return;
} // END print
/* ***************************************
* Define a method to
*/
public static void welcomeMessage ()
{
print("Thank you for playing the pet alien game");
print("In this game, you will have to look after your own alien.");
print("There is multiple aspects to looking after your alien, such as:");
print("Hunger, Behaviour and Thirst.");
print("");
print("When prompted, you can use the following commands:");
print("feed -> Replenishes alien to max hunger level");
print("drink -> Replenished thirst level to max");
print("");
return;
} // END
/* ***************************************
* Define a method to
*/
public void alienCreation ()
{
Alien ufo = new Alien();
ufo.name = userInput("What would you like to name your new alien?");
ufo.hungerRate = ranNum(1, 6);
print("On a scale of 1-6, your alien, " + ufo.name + ", has a hunger rate of " + ufo.hungerRate);
alienBehaviour(ufo.hungerRate);
return;
} // END alienCreation
public void alienBehaviour (int hunger) {
if (hunger <= 2){
print(ufo.name + " is very hungry, and is dangerously angry!!");
String action = userInput("You should feed it as soon as possible. (by typing 'feed')");
if (action.equals("feed")){
feedAlien();
}else if (action.equals("drink")) {
alienDrink();
}else{
print("That is a dangerous decision.");
}
}else if (hunger <= 4) {
print(ufo.name + " is mildly hungry, but is in a calm state.");
String action = userInput("Would you like to take any actions?");
if (action.equals("feed")){
feedAlien();
}else if (action.equals("drink")) {
alienDrink();
}else{
print("Okay.");
}
}else if (hunger <= 6) {
print(ufo.name + " is not hungry and is in a happy state.");
String action = userInput("Would you like to take any actions?");
if (action.equals("feed")){
feedAlien();
}else if (action.equals("drink")) {
alienDrink();
}else{
print("Okay.");
}
}
}
public void feedAlien() {
ufo.hungerRate = 6;
print(ufo.name + "'s hunger level replenished to max level 6.");
print(ufo.name + " is now at a happy level.");
}
public void alienDrink() {
ufo.thirst = 6;
print(ufo.name + "'s thirst level replenished to max level 6.");
}
public static int ranNum(int min, int max){ // A function that generates a random integer wihin a given range.
Random random = new Random();
return random.ints(min,(max+1)).findFirst().getAsInt();
} // END ranNum
} // END class alienPet
class Alien {
String name;
int age = 0;
int hungerRate;
int thirst = 6;
}
Obviously, some of the annotations are incomplete as of this time, but the issue I am having is in the alienBehaviour(), feedAlien() and alienDrink() procedures, I cannot seem to access the record created in the alienCreation() procedure.
The errors are all the same and is as follows:
alienPet.java:84: error: cannot find symbol
print(ufo.name + " is very hungry, and is dangerously angry!!");
^
symbol: variable ufo
location: class alienPet
Now I am new to java, so I'm not sure whether I have to make the record global or something, so any help would be greatly appreciated.
Variables declared inside of a method are called local variables and are likely disposed of when the method finishes executing.
Variables declared outside any function are called instance variables and they can be accessed (used) on any function in the program.
You are looking for an instance Alien ufo variable.
class alienPet{ // It is recommended you use the java naming convention.
Alien myAlien = new Alien();
// alienPet a = new alienPet();
// a.myAlien; // you could potentially do this to get an alien from an alienPet class
void someVoid(){
Alien otherAlien;
}
void errorVoid(){
otherAlien.toString();
// causes an error, the otherAlien variable is never visible to errorVoid as it is a local variable
myAlien.toString(); // OK
}
}
https://www.oracle.com/technetwork/java/codeconventions-135099.html
You're having problems with the scope of your variable. Variables are only valid within the curly braces which they were declared in.
WRONG
public void alienCreation ()
{
Alien ufo = new Alien();
ufo.name = userInput("What would you like to name your new alien?");
ufo.hungerRate = ranNum(1, 6);
print("On a scale of 1-6, your alien, " + ufo.name + ", has a hunger rate of " + ufo.hungerRate);
alienBehaviour(ufo.hungerRate);
return;
} // END alienCreation and of the scope of your variable ufo
RIGHT
class alienPet
{
Alien ufo;
[...]
public void alienCreation ()
{
ufo = new Alien();
ufo.name = userInput("What would you like to name your new alien?");
ufo.hungerRate = ranNum(1, 6);
print("On a scale of 1-6, your alien, " + ufo.name + ", has a hunger rate of " + ufo.hungerRate);
alienBehaviour(ufo.hungerRate);
return;
} // END alienCreation and your variable ufo will be initialized afterwards
}

It says 1 of 2 branches missed in java

I have 3 classes. I am trying to set a variable in the main method through an object called "main" and reuse that value by writing super.getnumberofsets(); in the for loop but it says "1 of 2 branches missed".
public static void main(){
//in the main method
//Main class maintain the private variables with their setters and getters.
Main main = new Main();
Sets sets = new Sets();
System.out.print("Enter how many sets you want to create: ");
newnumberofsets = in.nextInt();
main.set_numberofsets(newnumberofsets);
sets.setgroups();
sets.getgroups();
}
// in Sets class
protected void setgroups()
{
//In this loop it says "1 of 2 branches missed".
for(int x = 0; x<super.getnumberofsets();x++) {
main_zeroarray[x] = new Main0();
}
}
protected void getgroups() {
count = 1;
for(int x = 0 ;x < super.getnumberofsets();x++) {
System.out.println(count + ". Set " + setnames[x]);
count++;
}
}
I expected that the super keyword would read the same value from the object main.set_newnumberofsets(newnumberofsets);
The most likely explanation of there being a missed branch in the lopp is that that super.getnumberofsets() returns 0, so the loop terminating condition x < super.getnumberofsets() is false, thus the loop increment x++ is never executed, making it a "missed branch".

Unfair Candy Distribution

I am completing an assignment and am having a hard time figuring out the logic need to make the program work. I do not want a direct answer but could someone point me in the right direction?
Assignment:
Define a class named UnfairCandyDistributor. An UnfairCandyDistributor object represents a mean big brother who is going to divide a set of candies between himself and his hungry little brother. This will be done unfairly: for every candy given to the sibling, the big brother takes for himself a number of additional candies equal to the younger sibling's total. Each UnfairCandyDistributor object should have the same method:
public void nextCandy()
Each time nextCandy is called, the method prints a message about who gets a candy. Each call to nextCandy produces a single line of output. This time the output is the following:
public class TestCandy2 {
public static void main(String[] args) {
UnfairCandyDistributor mean = new UnfairCandyDistributor();
mean.nextCandy(); // 1 for you.
mean.nextCandy(); // 1 for me.
mean.nextCandy(); // 2 for you.
mean.nextCandy(); // 1 for me.
mean.nextCandy(); // 2 for me.
mean.nextCandy(); // 3 for you.
mean.nextCandy(); // 1 for me.
mean.nextCandy(); // 2 for me.
mean.nextCandy(); // 3 for me.
Here The class I have made so far:
public class UnfairCandyDistributor {
private int you;
private int me;
private int extra;
public void nextCandy()
{
if (you != me || extra != you - 1)
{
me++;
System.out.println(me + " for me");
}
else
{
you++;
System.out.println(you + " for you");
extra = 0;
}
}
}
Can't you just add a boolean variable that tells you who to dole out candy to?
public class UnfairCandyDistributor {
private int you = 0;
private int me = 0;
private boolean candyToMe = false;
public void nextCandy()
{
if (candyToMe)
{
for (int i=0; i<you; i++) {
System.out.println("one for me");
me++;
}
else
{
System.out.println("one for you");
you++;
}
candyToMe = !candyToMe;
}
}
or
public class UnfairCandyDistributor {
private int you = 0;
private int me = 0;
private boolean candyToMe = false;
public void nextCandy()
{
if (candyToMe)
{
System.out.println(you + " for me");
me += you;
}
else
{
System.out.println("1 for you");
you++;
}
candyToMe = !candyToMe;
}
}
..depending on whether you want the candies doled out one at a time or in hand-fulls where appropriate.

How to get input without pressing enter every time?

I made a simple game(well not really a game yet) in which the player can move in a room 4x20 characters in size. It runs in console.
But in my game loop I want to be able to move around in the room without pressing enter every time I want to move. The player should be able to press w/a/s/d and have the screen update instantly, but I don't know how to do that.
public class Main{
public static void main(String[] args){
MovementLoop();
}
public static void MovementLoop(){
Scanner input = new Scanner(System.in);
int pos=10, linepos=2;
String keypressed;
boolean playing = true;
while(playing == true){
display dObj = new display(linepos, pos);
dObj.drawImage();
keypressed=input.nextLine();
if(keypressed.equals("w")){
linepos -= 1;
}
else if(keypressed.equals("s")){
linepos += 1;
}
else if(keypressed.equals("a")){
pos -= 1;
}
else if(keypressed.equals("d")){
pos += 1;
}
else if(keypressed.equals("q")){
System.out.println("You have quit the game.");
playing = false;
}
else{
System.out.println("\nplease use w a s d\n");
}
}
}
}
public class display{
private String lines[][] = new String[4][20];
private String hWalls = "+--------------------+";
private String vWalls = "|";
private int linepos, pos;
public display(int linepos1, int pos1){
pos = pos1 - 1;
linepos = linepos1 - 1;
}
public void drawImage(){
for(int x1=0;x1<lines.length;x1++){
for(int x2=0;x2<lines[x1].length;x2++){
lines[x1][x2]="#";
}
}
lines[linepos][pos]="O";
System.out.println(hWalls);
for(int x2=0;x2<lines.length;x2++){
System.out.print(vWalls);
for(int x3=0;x3<lines[x2].length;x3++){
System.out.print(lines[x2][x3]);
}
System.out.println(vWalls);
}
System.out.println(hWalls);
}
}
The answer is simple
You can't do that
Because command line environment is different from swing, as swing can do such a thing as it deals with events and object, whereas, command line have no events.
So, maybe it's a right time to leave command line.

Issue setting instance variables

I am passing some coordinates from one class to another using the following code
**edited to show more detail
At start of class1:
public class BattleGui implements ActionListener {
private int xCoordinate;
private int yCoordinate;
public void coordinateHandler(int xCoord, int yCoord) {
xCoordinate=xCoord;
yCoordinate=yCoord;
System.out.println("Coordinates Received "+xCoord + " " +yCoord);
System.out.println("Test "+xCoordinate + " " +yCoordinate);
}
public void actionPerformed(ActionEvent e) {
String classname = getClassName(e.getSource());
JComponent component = (JComponent)(e.getSource());
cellState cs = new cellState();
if (classname.equals("JMenuItem")) {
JMenuItem menusource = (JMenuItem)(e.getSource());
String menutext = menusource.getText();
// Determine which menu option was chosen
if (menutext.equals("Load Game")) {
/* BATTLEGUI Add your code here to handle Load Game **********/
System.out.println(cs.turnFeedback());
LoadGame();
}
else if (menutext.equals("Save Game")) {
/* BATTLEGUI Add your code here to handle Save Game **********/
SaveGame();
}
else if (menutext.equals("New Game")) {
/* BATTLEGUI Add your code here to handle Save Game **********/
NewGame();
}
}
// Handle the event from the user clicking on a command button
else if (classname.equals("JButton")) {
JButton button = (JButton)(e.getSource());
int bnum = Integer.parseInt(button.getActionCommand());
int row = bnum / GRID_SIZE;
int col = bnum % GRID_SIZE;
//col=yCoord;
//row=xCoord;
//System.out.println(e.getSource());
//System.out.println(bnum / GRID_SIZE);
fireShot(row, col);
if (row==xCoordinate){
if (col==yCoordinate){
button.setBackground(cellColour[cs.turnFeedback()]);
}
else {
//Remember to change the 1 to whatever is reported back from cell class cell state
//button.setBackground(cellColour[cs.turnFeedback()]);
button.setBackground(Color.BLUE);
}
}
else {
button.setBackground(Color.BLUE);
}
}
}
From class2:
public void shipDeploy() {
int gridLength;
int lengthDraw;
int winningNumbers = 0;
int xCoord;
int yCoord;
xCoord=99;
yCoord=100;
System.out.println(xCoord + "\n" + yCoord);
BattleGui bGui = new BattleGui();
//Passing the coordinates back to the battlegui coordinate handler class
bGui.coordinateHandler(xCoord, yCoord);
}
This passes these two values to a coordinate handler method within the first class.
within this class I have an xCoordinate variable used throughout a variety of methods, the problem is that I dont seem to be able to set this, 0 is always being returned outside of this method for xCoordinate and yCoordinate and I dont understand why, as they seem to be ok in the line System.out.println("Test "+xCoordinate + " " +yCoordinate); above.
just figured it out on my own, quite simple really, actionlistener was basically re-instantiating the variable on every "event" explaining the zero values, as soon as i took this process outside of the listener it worked and set the values as intended. thanks for the input guys and hope this helps someone along the way!

Categories