How do I access a record from another procedure? - java

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
}

Related

How do I make a class to dynamic check different objects variable?

I'm new to Java, and i'm trying to create an automatic working shift schedule.
I want the code to mix four different employees to handle a morning shift and afternoon shift every work day.
I have made some code that just pick a random employee into a shift:
import java.util.Arrays;
import java.util.Random;
public class CreateNewShift {
public static void main(String[] args) {
int startWeek = 30; //Which week would start from?
int endWeek = 32; //which week will you end on?
generateShift(startWeek, endWeek);
}
private static void generateShift(int startWeek, int endWeek) {
String Employees[] = {"Employee1", "Employee2", "Employee3", "Employee4"};
String morningShift;
String afternoonShift;
for (int x = 0; x <= (endWeek - startWeek); x++) { //This is counting the number of weeks
System.out.println("\nWeek: " + (startWeek+x));
for (int i = 1; i <= 5; i++) { //this is finding the next working shift day
morningShift = p.chooseRandomEmployee(Employees);
afternoonShift = p.chooseRandomEmployee(Employees);
if (i == 1) {
System.out.println("Mon: " + morningShift + " + " + afternoonShift);
}
else if (i == 2) {
System.out.println("Tue: " + morningShift + " + " + afternoonShift);
}
else if (i == 3) {
System.out.println("Wed: " + morningShift + " + " + afternoonShift);
}
else if (i == 4) {
System.out.println("Thu: " + morningShift + " + " + afternoonShift);
}
else {
System.out.println("Fri: " + morningShift + " + " + afternoonShift);
}
}
}
}
public class Employee {
public String chooseRandomEmployee(String[] Employees) {
Random r = new Random();
int randomNumber = r.nextInt(Employees.length);
return Employees[randomNumber];
}
}
However, I now want the code to handle more restictions.
So i'm currently trying to add the option for the employees to choose some specific days that they dont want to have a shift. I have done this by adding this code to the Employee class:
public class Employee {
boolean monShift = true;
boolean tueShift = true;
boolean wedShift = true;
boolean thuShift = true;
boolean friShift = true;
public String chooseRandomEmployee(String[] Employees) {
Random r = new Random();
int randomNumber = r.nextInt(Employees.length);
return Employees[randomNumber];
}
}
And then i had tried to create new objects in my main class:
private static void generateShift(int startWeek, int endWeek) {
Employee Employee1 = new Employee("Employee1");
Employee Employee2 = new Employee("Employee2");
Employee Employee3 = new Employee("Employee3");
Employee Employee4 = new Employee("Employee4");
String Employees[] = {"Employee1", "Employee2", "Employee3", "Employee4"};
String morningShift;
String afternoonShift;
....
Quetions:
How can I improve my code in the Employee class to do a check if the random chosen employee have
monShift = true;
I have tried something like this, but i know it will not work, (and does not work either):
import java.util.Random;
public class Employee {
public String chooseRandomEmployee(String[] Employees) {
Random r = new Random();
int randomNumber = r.nextInt(Employees.length);
**if (("Employee" + randomNumber).monShift == false) {**
// Go back and try find a new random employee
}
else {
return Employees[randomNumber];
}
}
}
So i need a way to make my code dynamic to know which object (employee) it has to check if they are available that specific day or not.
Feel free to ask for a deepening if my question is not clear.
Since this i my first question on this forum, I also appriciate feedback if my question and thoughts are too long, or any other comments.
I dont think that putting the chooseRandomEmployee() function inside the Employee object is a good idea beacuse is not a part of the employee, is not an "action" of it. I think you shiudl put it outside but I want to respect your decision so shoudl check the do while loop.
import java.util.Random;
public class Employee {
public String chooseRandomEmployee(String[] Employees) {
int randomNumber;
do {
//Generate a new random number
Random r = new Random();
randomNumber = r.nextInt(Employees.length);
//The line under is the same that saying "If monSift == false return to
//the beginning and start again generating a new number"
} while ("Employee" + randomNumber).monShift == false);
return Employees[randomNumber];
}
}

Searching for a String in an ArrayList of Objects

I have been trying to figure this out for hours and I have had no luck doing so,
I'm trying to iterate over my Arraylist<Booking> which utilizes my Booking class file and trying to understand how I'm able to search it for the matching, case-insensitive term.
this is my current method:
private void searchBookings() {
if (bookings.size() <= 0) {
JOptionPane.showMessageDialog(null, "There are no bookings.", "Search Bookings", 3);
} else {
String searchTerm = JOptionPane.showInputDialog(null, "Please input search term: ", "Search Bookings", 3);
for (int i = 0; i < bookings.size(); i++) {
while (!bookings.get(i).getStudent().getName().equalsIgnoreCase(searchTerm)) {
i++;
if (bookings.get(i).getStudent().getName().equalsIgnoreCase(searchTerm)) {
String output = String.format("%-30s%-18s%-18b$%-11.2f\n", bookings.get(i).getStudent(), bookings.get(i).getLessons(), bookings.get(i).isPurchaseGuitar(), bookings.get(i).calculateCharge());
this.taDisplay.setText(heading + "\n" + output + "\n");
}
}
}
}
JOptionPane.showMessageDialog(null, "There is no booking with that name.", "Search Bookings", 3);
}
I know it's messy but, just trying to make do.
I am trying to retrieve the name of the booking as I am searching by name as well as provide an error message if that names does not exist, to do that I must
use bookings.getStudent().getName() I have had some luck as I can return the value but now I am not able to provide my error message if I do not find it. Any help is appreciated.
package com.mycompany.mavenproject1;
public class Booking {
private Student student;
private int lessons;
private boolean purchaseGuitar;
// CONSTANTS
final int firstDiscountStep = 6;
final int secondDiscountStep = 10;
final int tenPercentDiscount = 10;
final int twentyPercentDiscount = 5;
final double LESSON_COST = 29.95;
final double GUITAR_COST = 199.00;
double LESSON_CHARGE = 0;
final int MINIUMUM_LESSONS = 1;
public Booking() {
}
public Booking(Student student, int lessons, boolean purchaseGuitar) {
this.student = new Student(student.getName(), student.getPhoneNumber(), student.getStudentID());
this.lessons = lessons;
this.purchaseGuitar = purchaseGuitar;
}
public Student getStudent() {
return student;
}
public void setStudent(Student student) {
this.student = student;
}
public int getLessons() {
return lessons;
}
public void setLessons(int lessons) {
this.lessons = lessons;
}
public boolean isPurchaseGuitar() {
return purchaseGuitar;
}
public void setPurchaseGuitar(boolean purchaseGuitar) {
this.purchaseGuitar = purchaseGuitar;
}
public double calculateCharge() {
double tempCharge;
if (lessons < firstDiscountStep) {
LESSON_CHARGE = (lessons * LESSON_COST );
} else if (lessons < secondDiscountStep) {
tempCharge = (lessons * LESSON_COST) / tenPercentDiscount;
LESSON_CHARGE = (lessons * LESSON_COST) - tempCharge;
} else {
tempCharge = (lessons * LESSON_COST) / twentyPercentDiscount;
LESSON_CHARGE = (lessons * LESSON_COST) - tempCharge;
}
if (isPurchaseGuitar()) {
LESSON_CHARGE += GUITAR_COST;
}
return LESSON_CHARGE;
}
#Override
public String toString() {
return student + ","+ lessons + "," + purchaseGuitar +"," + LESSON_COST;
}
}
If I understood you correctly, you are searching for a given student name in your collection of bookings. And if it is present, set a formatted text.
First of all, use a for-each loop, because you don't use the index.
Secondly, return from the for-each loop, when you found your student.
private void searchBookings() {
if (bookings.size() <= 0) {
JOptionPane.showMessageDialog(null, "There are no bookings.", "Search Bookings", 3);
} else {
String searchTerm = JOptionPane.showInputDialog(null, "Please input search term: ", "Search Bookings", 3);
for (final Booking booking : bookings) // for-each
{
if (booking.getStudent().getName().equalsIgnoreCase(searchTerm))
{
String output = booking.getFormattedOutput();
this.taDisplay.setText(heading + "\n" + output + "\n");
return; // break out of the loop and method and don't display dialog message
}
}
}
JOptionPane.showMessageDialog(null, "There is no booking with that name.", "Search Bookings", 3);
}
Then there are multiple other things, which you could improve.
Don't get all the data from a booking just to format it externally. Let the Booking class handle the formatting and return you the string you desire. (move the formatting in a function inside the Booking class)
Instead of recreating a Student you receive in your Booking constructor, make the Student class immutable, and then you can just reuse the object provided.
Try also making the Booking class immutable. You provided some setters, but do you really want to change the student in a booking? Or would you rather create a new booking for the other student?
The calculteCharge method could be stateless. Just get the LESSON_CHARGE value and hold it in a local variable. Your method would also get threading-proof.
Make your constants final and better yet make them members of the class (by adding the static modifier) instead of every member.
Lastly, representing a money amount with a floating (double is better but not good either) number, you will run into funny situations. Try this calculation: 0.1+0.1+0.1+0.1+0.1+0.1+0.1+0.1+0.1+0.1 for example.
One way would be to create a Money class which holds the value in cents as an integer. And when you want to display the amount you can divide it by 100 and format it accordingly. That way, you can also restrict it become negative.
PS: Sometimes we desperately try to find a solution that we don't give ourselves some rest. After a little break, you might recognize the problem. Oh and try debugging with breakpoints. Or this, if you use IntelliJ IDEA (which I would highly recommend, the community edition is free).
You're re-incrementing your counter variable, which is really not going to help. Try the following:
private void searchBookings() {
if (bookings.size() <= 0) {
JOptionPane.showMessageDialog(null, "There are no bookings.", "Search Bookings", 3);
} else {
String searchTerm = JOptionPane.showInputDialog(null, "Please input search term: ", "Search Bookings", 3);
boolean studentFound = false;
for (int i = 0; i < bookings.size(); i++) {
if (bookings.get(i).getStudent().getName().equalsIgnoreCase(searchTerm)) {
String output = String.format("%-30s%-18s%-18b$%-11.2f\n", bookings.get(i).getStudent(),
bookings.get(i).getLessons(), bookings.get(i).isPurchaseGuitar(),
bookings.get(i).calculateCharge());
this.taDisplay.setText(heading + "\n" + output + "\n");
studentFound = true;
break;
}
}
}
if (!studentFound) {
JOptionPane.showMessageDialog(null, "There is no booking with that name.", "Search Bookings", 3);
}
}

string choice condition is met, class is not called

EDIT again:
each time I run this and input the "String a", all methods get called and I don't know why.
I know its all newbie stuff but counter intuitively, there are too many tutorials and threads on java to properly troubleshoot basic issues like this.
import java.util.*;
public class ShopTest {
public static Scanner navigate = new Scanner(System.in);
public static Scanner playerStats = new Scanner(System.in);
public static Scanner shop = new Scanner(System.in);
static int playerGold = 0;
static String items;
static int ironSword = 200;
static int rustySword = 75;
static int lightLeatherArmor = 50;
static int minorHealthpotion = 25;
static String bought = "item added to inventory";
static String notBought = "Sorry, you don't have enough for that!";
public static void main(String[] args) {
System.out.println("Welcome player.\nWhat is your name?");
String playerName = playerStats.next();
System.out.println("\nAh!" + playerName + "\n\nWe've been expecting you.\nAs we agreed, you get half the gold now and half after you kill that goblin!\nYou recieved 150 gold.");
playerGold = playerGold +150;
Navigate();
}
public static void Shop() {
System.out.println("\nWelcome to my shop\nWould you like to see my wares?");
String shopChoice1 = shop.next();
if (shopChoice1.equals("yes")) {
System.out.println("\nSee anything you need?\nIron sword: " + ironSword + "\nRusty sword: " + rustySword + "\nLight leather armor: " + lightLeatherArmor + "\nMinor health potion: " + minorHealthpotion);
}
String shopChoice2 = shop.next();{
System.out.println("ok");
if (shopChoice2.equals("iron sword")) {
IronSword();}
else if (shopChoice2.equals("rusty sword")) {
RustySword();}
else if (shopChoice2.equals("light leather armor")) {
LightleatherArmor();}
else if (shopChoice2.equals("minor health potion")) {
MinorhealthPotion();}
else if (shopChoice2.isEmpty()) {
Shop();}
}
}
public static void IronSword() {
if (playerGold >= ironSword)
System.out.println(bought);
items = items + "Iron sword,\n";
if (playerGold < ironSword)
System.out.println(notBought);
Shop();
}
public static void LightleatherArmor() {
}
public static void RustySword() {
if (playerGold >= rustySword)
System.out.println(bought);
items = items + "Rusty Sword,\n";
if (playerGold < rustySword)
System.out.println(notBought);
Shop();
}
public static void MinorhealthPotion() {
}
public static void Inn() {
System.out.println("**You enter the inn and approach the barkeep**\nHow can I help you?");
}
public static void Inventory() {
System.out.println("Gold: " + playerGold + "\nItems: \n" + items + "\n\n");
Navigate();
}
public static void Navigate() {
System.out.println("\nWhat next?\n Shop\n Inn\n Inv");
String a = navigate.nextLine();
if (a.equals("shop"))
Shop();
else if (a.equals("inn"))
Inn();
else if (a.equals("inv"))
Inventory();
}
}
*need add more text for some reason!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!*need add more text for some reason!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!*need add more text for some
The default delimiter for the Scanner is whitespace. Which means it will break up the string on every whitespace (space, tabs, newlines). So if you enter "iron sword" you will only get "iron" on shop.next() and "sword" on the call after.
Since you want to read in whole lines, you can set the Delimiter to a newline. Like this:
public static Scanner shop = new Scanner(System.in).useDelimiter("\\n");
The Javadoc for the Scanner class mentions this: https://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html
BTW: Which IDE do you use? If you are new to programming make yourself familiar with it's debugging features. You can set a breakpoint right after the shop.next() call and then inspect the content of shopChoice2. This would have shown you that shop.next() does not do what you expect it to do.
EDIT:
There is a mistake after you edited your code:
if (shopChoice2.equals("iron sword"))
System.out.println("ok");
IronSword();}
if (shopChoice2.equals("rusty sword"))
This should be:
if (shopChoice2.equals("iron sword")) {
System.out.println("ok");
IronSword();}
} else if (shopChoice2.equals("rusty sword"))
Only "System.out.println("ok");" is being called if the if statement is true. Note that only the next statement is called if an "if" statement is true. If you need more that one statement to be executed you need to enclose those in curly brackets. As a general rule one should ALWAYS use curly brackets with if statements. Even if there is only one statement. This helps avoiding making mistakes like that.
EDIT 2:
This should work. Find the differences to your code:
String shopChoice2 = shop.next();
System.out.println(shopChoice2);
if (shopChoice2.equals("iron sword")) {
IronSword();"
} else if (shopChoice2.equals("rusty sword")) {
RustySword();
} else if (shopChoice2.equals("light leather armor")) {
LightleatherArmor();
} else if (shopChoice2.equals("minor health potion")) {
MinorhealthPotion();
} else if (shopChoice2.isEmpty()) {
Shop();
}

How to compare parameter values of two objects in Java?

Right now I'm working on a method for comparing the scores of athletes in the olympics. So far I've had little trouble, however now I've reached a point where i need to compare two objects (athletes) scores and I'm not sure how to do it. This is my code for the Olympic class:
// A program using the Athlete class
public class Olympics {
public static void main(String args[]) {
System.out.println("The leader is " + Athlete.leader() +
", with a score of " + Athlete.leadingScore());
Athlete meryl = new Athlete("Meryl Davis", "U.S.");
meryl.addScore(75);
System.out.println(meryl);
Athlete tessa = new Athlete("Tessa Virtue", "Canada");
System.out.println(tessa);
System.out.println(); // blank line
tessa.addScore(50);
System.out.println(tessa);
System.out.println(meryl);
System.out.println("The leader is " + Athlete.leader() +
", with a score of " + Athlete.leadingScore());
System.out.println(); // blank line
tessa.addScore(100);
meryl.addScore(65);
System.out.println(tessa);
System.out.println(meryl);
System.out.println("The leader is " + Athlete.leader() +
", with a score of " + Athlete.leadingScore());
System.out.println(); // blank line
tessa.addScore(20);
System.out.println("Tessa's final score is " + tessa.getScore());
meryl.move("France");
System.out.println(meryl);
} // end main
} // end class Olympics
And this is the constructor class "Athlete":
public class Athlete {
private String name;
private String country;
protected int score;
public static int leadScore;
public Athlete(String athName, String athCountry) {
this.name = athName;
this.country = athCountry;
score = 0;
if (score < 1) {
System.out.println("Score cannot be lower than 1");
}
}
public int addScore(int athScore) {
score += athScore;
return score;
}
public static String leader(){
//TODO
}
public static int leadingScore() {
//MUST COMPARE BOTH ATHLETES
}
public int getScore(){
return score;
}
public void move(String newCountry) {
country = newCountry;
}
public String toString() {
return name + ": " + "from " + country + ", current score " + score;
}
}
So what I'm trying to do is have the program check Meryl's score compared to Tessa's and return that Athlete's score in leadingScore() and, using that athlete, return a leader(). Any help is appreciated! Thanks.
The function must take the two Athletes you're comparing as the parameters for this to work
public static int leadingScore(Athlete a1, Athlete a2) {
if (a1.getScore() < a2.getScore()) {
// do stuff
}
}
The lead score should not be in the athlete class, but rather in main () because one instance of an Athlete class would not know of other instances unless you put a self-referential list inside the class. Similarly, leadingScore should be in main ().
It or main can call each athlete and compare:
int merylScore = meryl.getScore ();
int tessaScore = tessa.getScore ();
int leadingScore = 0;
String leaderName = "";
if (merylScore > tessaScore) {
leadingScore = merylScore;
leaderName = meryl.getName ();
} else if (tessaScore > merylScore) {
leadingScore = tessaScore;
leaderName = tessa.getName ();
} else {
leadingScore = merylScore;
leaderName = "a tie between Meryl and Tessa";
}
System.out.println ("The leader is " + leaderName + ", with a score of " + leadingScore);
You should consider using a "collection". Use an array, a list ... or even a sorted list.
Stored your individual objects in the collection, then traverse the collection to find the highest score.
For example:
// Create athlete objects; add each to list
ArrayList<Athlete> athletes = new ArrayList<Athlete>();
Athlete meryl = new Athlete("Meryl Davis", "U.S.");
meryl.addScore(75);
...
athletes.add(meryl);
Athlete tessa = new Athlete("Tessa Virtue", "Canada");
...
athletes.add(tessa );
// Go through the list and find the high scorer
Athlete highScorer = ...;
for (Athlete a : athletes) {
if (highScorer.getScore() < a.getScore())
highScorer = a;
...
}
System.out.println("High score=" + highScorer.getScore());
Here's a good tutorial:
http://www.vogella.com/tutorials/JavaCollections/article.html

Unable to increment variable (object oriented programming)

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.

Categories