play.java: https://pastebin.com/4bzfE76z
values.java: https://pastebin.com/6mnUzKyA
player.java: https://pastebin.com/qiFymMF6
stats.java: https://pastebin.com/P24AUpXV
I have a method called start in play.java with object parameters. The objects were originally declared in values.java inside the sValues method. I want to call the method start to the main method of play.java but I'm not sure what to write inside the parameters of the call.
Inside values.java:
player user = new player ();
user.setP_Name (username);
user.setP_ATK (atk);
user.setP_HP (hp);
stats[] enemies = new stats [3];
enemies [1] = new stats ();
enemies [1] = gob;
enemies [1].getName ();
enemies [1].getHP ();
enemies [1].getATK ();
enemies [1].getMANA ();
enemies [2] = new stats ();
enemies [2] = orc;
enemies [2].getName ();
enemies [2].getHP ();
enemies [2].getATK ();
enemies [2].getMANA ();
Inside play.java, I use the objects like this:
System.out.println ("Hitpoints[HP]: " + enemies [i].getHP ());
and it works great because I included these two objects into the parameter of the method:
public static void start (player user, stats[] enemies)
However, whenever I want to call start in the main method for it to do the things I want it to, it gives me errors. This is how I've been trying to call it:
public static void main (String[] args)
{ //main method
start(player, stats);
} //main method
Am I doing something wrong? Any help appreciated. I'll gladly add more information if needed. New to coding and not sure what specific details need to be provided.
My errors:
{ //main method
player player = new player();
start(player, stats);
} //main method
Error on: start(player, stats);
Cannot find symbol. Symbol: variable stats. Location: class play.
This error is given when I hover over "stats" when using netbeans.
The main method is the entry point of your program. You have not instantiated anything else yet so there are no objects to pass into your start method.
You might need to give us more of your code, but you might need to try something like this first - and I this is making a lot of assumptions about your code
public static void main (String[] args)
{ //main method
Player player = new Player(); // This is an instance of your Player class
// and initialize your stats array.
Values v = new Values();
start(player, stats);
} //main method
Also providing the error you are getting may help also.
EDIT
After reviewing your code I can see some problems. In your Values class you have the method sValues which creates the enemies as you said, however they stats[] that you created in that method only has the scope of that method, so when that method is finished, the enemies you created have now disappeared.
You also have a lot of static reference - this is bad practice and you need to remove as much as possible. To do this you can change something like
Values.sValues();
to
Values v = new Values(); // in the constructor call what you need to
v.sValues();
You need to think about where you are going to store your enemies stats array. You could move it to the top of your Values class and add a getter for it then your code could look like this
Values.java
public class values {
public static String clear = "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n";
public static String username;
public static int atk = 1;
public static int hp = 10;
private stats[] enemies;
// .. your other code
public void sValues () // this method should not be static
{ //sValue method
// .. other code
enemies = new stats [3]; // Remove the declaration at the start of this line
// .. other code
}
public stats[] getEnemies()
{
return enemies;
}
Play.java
public static void main (String[] args)
{
// Create a player
player player = new player("Steve", 10, 10);
// Initialise your values
Values v = new Values();
// create the enemies (this could be done in your values constructor)
v.sValues();
// Start with these enemies
start(player, v.getEnemies());
}
Seems to me you have to create an instance of values.java and then get the player and stats objects from there to pass on to the main method. where are player, stats being declared in the play.java class?
try:
{
player player = new player();
stats[] stats = new stats[5];
start(player, stats);
} //main method
and initialize stats array with desired values
Related
This is regarding a Java homework assignment:
I want to create a method that takes the list of cards as a parameter and prints all the cards to the screen. Each card should print all stored information so that I can use the newly created method to print all the cards. And it is required for me to use the Array list of Card objects as a parameter.
I have three class in this program, namely - Main.java, HandDrawn.Java, and Card.java. Basically the program tracks the Christmas card information with the sender's name and if they are hand written or not. I'm stuck at this point as I don't know how to use ArrayLists properly and pass them through a method in order to print them.
public class Main {
public ArrayList<Card> cardsList = new ArrayList<>();
public static void main (String [] args){
Main myApp = new Main();
}
public void printAll (ArrayList<Card> cardArrayList){
System.out.println(cardArrayList);
HandDrawn sender1 = new HandDrawn("Anna", true);
HandDrawn sender2 = new HandDrawn("Kalle", false);
cardsList.add(0, sender1);
cardsList.add(1, sender2);
}
public void printing(ArrayList<Card> cardsList) {
System.out.println(cardsList);
}
}
Please see this examples:
how to print ArrayList in java
System.out.println("Print Arraylist using for each loop");
for( String strDay : aListDays ){
System.out.println(strDay);
}
Your logic does print the List before ot has anything in it. Try adding something to the List before printing the content.
public void printAll (ArrayList<Card> cardArrayList){
System.out.println("List content: " + cardArrayList.toString()); // <- Empty List at this point
HandDrawn sender1 = new HandDrawn("Anna", true);
HandDrawn sender2 = new HandDrawn("Kalle", false);
cardsList.add(0, sender1);
cardsList.add(1, sender2);
}
The output is then:
List content: []
Having difficulty calling the methods in my Game class to my main method for my hangman game.
We're supposed to spin a wheel to get a jackpot amount for 100,250 or 500 bucks then play the game as you'd expect... But methods are a necessity. Im nowhere near done I just want to be able to call my methods at this point to see how its working.
Here's my code:
import java.util.Scanner;
import java.util.Random;
public class GameDemo {
public static void main(String[] args) {
String[] songs = {"asdnj", "satisfaction", "mr jones",
"uptown funk"}; //note this is a very short list as an example
Random rand = new Random();
int i = rand.nextInt(songs.length);
String secretword = songs[i];
System.out.print("Welcome to The Guessing Game. The topic is song titles. \nYou have 6 guesses. Your puzzle has the following letters: ");
System.out.print("After spinning the wheel, you got " + spinWheel());
//continue the code here.
}
}
class Game {
Random rand = new Random();
String[] songs = {"asdnj", "satisfaction", "mr jones",
"uptown funk"};
int i = rand.nextInt(songs.length);
private String secretword = songs[i];
private char [] charSongs = secretword.toCharArray();
private char [] guessed = new char [charSongs.length];
private int guesses;
private int misses;
private char letter;
private char [] jackpotAmount = {100,250,500};
public Game (){}
public int spinWheel(int[] jackpotAmount){
int rand = new Random().nextInt(jackpotAmount.length);
return jackpotAmount[rand];
}
public char guessLetter(char charSongs [], char letter){
int timesFound = 0;
for (int i = 0; i < charSongs.length; i++){
if (charSongs[i] == letter){
timesFound++;
guessed[i] = letter;
}
}
return letter;
}
}
And the return error is
GameDemo.java:11: error: cannot find symbol System.out.print("After
spinning the wheel, you got " + spinWheel()); ^
To call methods from another class you need to make the method public. Once that is done, make them static if you will call the same method many times and you want it do the same function each time (the parameters can still be different).
To call the method do the following (this is a general form for most classes and methods, you should be able to use this to call all your methods):
yourClassWithMethod.methodName();
There are several issues in your spinWheelmethod call:
You haven't instantiated any any Game object to call this method. Either you have to make it static or just instantiate a Game and call it from that objet. I personally prefer the second (non-static) option because, especially because a static method cannot access directly non-static method or variables (... you need an instance or to make them static).
In main, you can do this (non-static solution):
Game game = new Game();
System.out.print("After spinning the wheel, you got " + game.spinWheel());
spinWheel requires an argument of type int[]. It seems that it is not useful since there is an instance variable jackpotAmount that seems to have been created on that purpose. jackpotAmount (see also second point) should be static in you example.
spinWheel becomes :
//you can have "public static int spinWheel(){"
//if you chose the static solution
//Note that jackpotAmount should also be static in that case
public int spinWheel(){
int rand = new Random().nextInt(jackpotAmount.length);
return jackpotAmount[rand];
}
Note that jackpotAmount should better be an int[]than a char[]
I have written a method (part of a program) which takes in two int values(code below). One int value representing number of guys for whom java training is completed and another int value for guys for whom php training is completed. I expect the arraylist to grow with every function call. Example: First time I called the function with values (5,0). So the arrayList for java would be [5] and for php it would be [0] . Next time I call the function with values (2,3). The arrayList for java should now be [5][2] and sum should be 7. The the arraylist for php should be [0][3] ans sum should be 3. The problem with my code is that when I call the method for the second time, it wipes away the [5](value of first index from the first call) in the java arrayList and just takes the form of [2] and gives the sum 2(instead of the required 7). The arrayList is never growing. (same for the php arrayList) I am sure I am doing something conceptually wrong here . Please help Somehow, the way I have coded it, every function call seems to make a new arrayList and not growing the arrayList obtained from the previous call.
public class TrainingCamp {
public static int trainedJavaGuys ;
public static int trainedPHPGuys ;
public void trainedTroopsInCamp(int java,int php){
//System.out.println("********* Current Status of Training Camp ********* ");
ArrayList<Integer> trainingListJava = new ArrayList<>();
trainingListJava.add(java);
//System.out.println("---JavaARRAYLIST----"+trainingListJava);
trainedJavaGuys = sumList(trainingListJava);
ArrayList<Integer> trainingListPHP = new ArrayList<>();
trainingListPHP.add(php);
trainedPHPGuys = sumList(trainingListPHP);
//System.out.println("---phpARRAYLIST----"+trainingListPHP);
Calling it like this from another class:
TrainingCamp currentTrainingCamp = new TrainingCamp();
currentTrainingCamp.trainedTroopsInCamp(2, 0);
and next time the same two lines get executed with just the input params changed
The arraylists are reinitialized each time you call trainedTroopsInCamp() because they are declared within it.
You should make the arraylists member variables, so that they only get initialized once, in the class's constructor.
public class TrainingCamp {
public static int trainedJavaGuys ;
public static int trainedPHPGuys ;
// Declare once
ArrayList<Integer> trainingListJava;
ArrayList<Integer> trainingListPHP;
public TrainingCamp() {
// Initialize once
trainingListJava = new ArrayList<>();
trainingListPHP = new ArrayList<>();
}
public void trainedTroopsInCamp(int java,int php){
// Use everywhere
trainingListJava.add(java);
trainedJavaGuys = sumList(trainingListJava);
trainingListPHP.add(php);
trainedPHPGuys = sumList(trainingListPHP);
}
}
you're re-initializing the list references in the method call, so every time you call the method you're using a new (empty) list.
instead, try keeping the lists as member variables for your class, something like this:
class TrainingCamp {
private final List<Integer> javaTrained = new LinkedList<>();
private final List<Integer> phpTrained = new LinkedList<>();
public void trainedTroopsInCamp(int java,int php){
//System.out.println("********* Current Status of Training Camp ********* ");
javaTrained.add(java);
trainedJavaGuys = sumList(javaTrained);
phpTrained.add(php);
trainedPHPGuys = sumList(phpTrained);
}
...
}
I'm making a text based adventure game with java, im a first year computer science student.
I made a room, exit, creature, item and world class and put in the API that was given to me in the class. It was just basic methods and some constructors.
We're suppose to create a textAdventure class were we bring together all the other classes and create the game.
The player and game class was given to me and my professor did all the necessary code in order to make the game run in that class.
My problem is I don't know how to start in my TextAdventure Class, also thats where my main method is.
So I'm confused on how to make a starting room and how to put an exit in that room leading to another room.
Here's some code
public class MyTextAdventure {
private Room room1;
private Room room2;
private Room room3;
private Room room4;
private Room room5;
private Room room6;
private Room room7;
private Room room9;
private Room room10;
public static void main(String [] args){
}
If I wanted to make a player start in room1, can I just do this.
public static void main(String [] args){
public Room startingRoom;
}
I have already declared startingRoom in the room class.
I'm sorry if my skills are bad, I just have no idea what I'm doing and where to start.
Use an array to keep track of your rooms. This allows you to avoid having to keep track of 10 different variable names. It also allows you to do math on the array index. For example, if you wanted to set the current room from 3 to 4, you wouldn't have to check which room was set to current. You could just do currentRoom++
Try something like this.
public class MyTextAdventure {
private Room[] rooms; //array for all rooms
int currentRoom = 0;
boolean over;
//class constructor
public MyTextAdventure() {
rooms = new Room[10]; //Initialize new room array of size 10
over = false; //game is not over yet
for(int i = 0; i < rooms.length; i++) {
//Initialize all rooms
rooms[i] = new Room();
}
}
public void start() {
//do your game loop in here
while(!over) {
}
}
}
public static void main(String [] args){
MyTextAdventure adventure = new MyTextAdventure();
adventure.start();
}
The main function should just start your game. Functions and classes should be designed to accomplish a singular task that is clear. Name classes, functions and variables so that you know exactly what they are doing.
Using the current room as an integer allows you to make use of it as an array index. For example if you want to get the current room you can do this for a function.
public Room getCurrentRoom() {
return rooms[currentRoom];
}
package bankAccount;
public class CurrentAccount {
int account[];
int lastMove;
int startingBalance = 1000;
CurrentAccount() {
lastMove = 0;
account = new int[10];
}
public void deposit(int value) {
account[lastMove] = value;
lastMove++;
}
public void draw(int value) {
account[lastMove] = value;
lastMove++;
}
public int settlement() {
int result = 0;
for (int i=0; i<account.length; i++) {
result = result + account[i] + startingBalance;
System.out.println("Result = " + result);
}
return result;
}
public static void main(String args[]) {
CurrentAccount c = new CurrentAccount();
c.deposit(10);
}
}
At the moment, when I run the class, the expected System.out.println does not appear, and if I simply move public static void main(String[] args) to the top, this generates multiple red points. What is the best way for me to refactor my code so it works in the expected way?
you can have another class called Main in the file Main.java in which you can write your
public static void main(String args[])
and call
c.settlement();
in you main() to print.
Also one more advice,
in your constructor you have
account = new int[10];
which can hold only 10 ints.
in your deposit() and draw() you are not checking the account size. When the value of lastMove is more than 10 , the whole code blows up.
Hence I suggest you to use ArrayList
You never called the settlement method...
public static void main(String args[]) {
CurrentAccount c = new CurrentAccount();
c.deposit(10);
c.settlement();
}
I have the feeling that you come from some non-OOP language, like C or PHP. So some explanation:
The main method is static: that means it "exists" even when there is no object instance created, it can be thought of as if it belonged to the class instance.
on the contrary, for the other methods to "work", an instance is required.
This way the main method can be (and is actually) used as the entry point of the application
It is executed, and when it exists, (if no other threads are left running) the application terminates.
so nothing else is run that is outside of this method just by itself...
so if you don't call c.settlement(); - it won't happen...
Other notes:
Running main doesn't create an instance of the enclosing class
with new CurrentAccount(), you create an object instance, which has states it stores, and can be manipulated
be careful with arrays, they have to be taken care of, which tends to be inconvenient at times...
Why do you expect the printed output to appear? You don't actually call the settlement method, so that command is not executed.
You did not call settlement.. so nothing appears
if you add c.settlement... it is fine..
You have not called deposit() and settlement() in the main method untill you call, You cannot get expected output.