Java: setting a objects variable in outside function - java

public static void main(String[] args) {
Player Anfallare = new Player("A");
Player Forsvarare = new Player("F");
MotVarandra(Anfallare.getDice(1), Forsvarare.getDice(1));
(...)
}
Is what I have in main function, now I made a own function,
public static void MotVarandra(int a, int f){
if(f >= a){
Anfallare.armees-=1;
}else{
Forsvarare.armees-=1;
}
}
which should set the object's variable to -=1.. But this doesn't work because the function doesnt know that Anfallare and Forsvarare is an object..
What can i do in this case?

You need to define the Players as class fields, instead of inside the main method.
For a gentle introduction to Java, I suggest you to start reading here:
http://download.oracle.com/javase/tutorial/java/index.html
Also, there are great book suggestions here: https://stackoverflow.com/questions/75102/best-java-book-you-have-read-so-far . Some of those books are great to begin learning.
Example here:
public class Game {
private static Player Anfallare, Forsvarare; // <-- you define them here, so they are available to any method in the class
public static void main(String[] args) {
Anfallare = new Player("A"); // <-- it is already defined as a Player, so now you only need to instantiate it
Forsvarare = new Player("F");
MotVarandra(Anfallare.getDice(1), Forsvarare.getDice(1));
// ...
}
public static void MotVarandra(int a, int f){
if(f >= a){
Anfallare.armees-=1; // <-- it is already defined and instantiated
}else{
Forsvarare.armees-=1;
}
}
}

While Aleadam's solution is by far the best answer, another thing you could do to specifically resolve this issue is change the arguments of the function:
public static void MotVarandra(Player a, Player f){
if(f.getDice(1) >= a.getDice(1)){
f.armees-=1;
}else{
a.armees-=1;
}
}
Ultimately, your optimal solution just depends on what your program is doing. Chances are, this is just another way of looking at it.
As a side note, be sure to use descriptive naming techniques, a and f are somewhat hard coded, and only make sense if you use only those variable names for your Players. It's best to not potentially limit your code.

Related

Question about Berkeley Data Structures Free Online Course (CS61B) Tutorial question on static variables in Java

Note: This is not a homework assignment, but a free course that anyone can access.
The course can be found at: https://sp18.datastructur.es/index.html
The tutorial question can be found at: https://sp18.datastructur.es/materials/discussion/examprep02sol.pdf
Also, the variables are named as such in order to confuse potential students, and I decided not to change it for fear of changing the code resulting in a different output. Also, some of the variables (baby), and method calls were not used at all, but I have retained it in order to keep to the original question.
Q1 Write what the main method will print out once it is executed. It might be helpful to draw box and pointer diagrams to keep track of variables (Spring ’15, MT1)
public class Shock {
public static int bang;
public static Shock baby;
public Shock() {
this.bang = 100;
}
public Shock(int num) {
this.bang = num;
baby = starter();
this.bang += num;
}
public static Shock starter() {
Shock gear = new Shock();
return gear;
}
public static void shrink(Shock statik) {
statik.bang -= 1;
}
public static void main(String[] args) {
Shock gear = new Shock(200);
System.out.println(gear.bang); //300
shrink(gear);
shrink(starter());
System.out.println(gear.bang); //99
}
}
Why is the value of gear.bang 300 instead of 200 + 200? I understand that gear is a static variable, but when using the second constructor, the value 100 should not have been involved at all. I would have thought that the static variable bang would be set as 200, then 200 += 200 will result in the static variable bang being 400 for all instances of Shock class. Why is gear.bang 300 instead?
The second constructor calls starter().
starter() calls new Shock().
The Shock() constructor sets bang to 100. Then 200 is added to bang. So bang is 300.

How to create boolean array in global - Java

I want create Boolean array in global, here code i tried to make
public class BettingHandler extends BaseClientRequestHandler
{
public static int player[] = new int [100];
public static int i;
public static boolean playerAct[];
public void handleClientRequest(User user, ISFSObject params)
{
RouletteExtension gameExt = (RouletteExtension) getParentExtension();
if (BettingHandler.player[BettingHandler.i] != -1)
{
trace("player problem");
BettingHandler.player[BettingHandler.i] = user.getPlayerId();
BettingHandler.playerAct[BettingHandler.i] = true;
i++;
}
trace("If this showed, no error");
}
}
In Eclipse not showed redcross sign in left this code
public static boolean playerAct[];
and here
BettingHandler.playerAct[BettingHandler.i] = true;
I make this for handler in SFS2X, so i check error in SFS2X zone monitor but unfortunately, this script just run till this
trace("player problem");
when remove this code
BettingHandler.playerAct[BettingHandler.i] = true;
script run till this
trace("If this showed, no error");
so i know something wrong with BettingHandler.playerAct[BettingHandler.i] = true;, How could I fix my code?
You never initialized the array but you are trying to use it.
public static boolean playerAct[] = new boolean[100];
Funny thing:
public static int player[] = new int [100];
public static int i;
public static boolean playerAct[];
The first array, there you actually create an array for 100 elements.
You omit that step for your second array. And you are really surprised that the second gives you problems?
Besides: whatever framework your are working with; maybe you should first step back and learn some more about the basics of Java. For example, the above code might work when fixed; but doing everything with public static variables ... looks very much like bad design.

I keep running into the same problems every time I try to make a new program

My current program is a simple game.. I am trying to make it to help figure out how to properly use OOP. But every time I get a little bit into a new program I run into the same problem:
I make an instance to use in my game. This instance could be anything - the main hero, a monster, whatever. Everything is going good, the instance is exactly what I want it to be. Maybe I manipulate it a little bit.
I then try to use a different class, I guess I create an instance of a different class, in an attempt to further manipulate the original instance. Maybe I originally created my hero and changed his stats, and now at this point I am trying to have my hero say something based on the stats that were chosen.
This point is always where I hit a roadblock. I can't seem to do what I want to do here - I can't use that original instance I made because It was just an instance and I don't know how to manipulate it(or even if I am supposed to) from within a new class.
So.. it's a fundamental design problem/lack of understanding of OOP.
But I feel like I have a decent grasp on how to actually program stuff.. I keep reading and reading and getting advice but I can't seem to get past this barrier.
I know people on this site don't seem to like posts like this but maybe someone here can Identify with what it is I am not grasping.
Here is an example of what I am talking about, the game I am trying to make right now.
package pkgnew.stupid.game;
import java.util.Scanner;
/**
*
* #author whyguy2
*/
public class Hero {
public static int heroattack = 1;
public static int herospeed = 1;
public static int heroarmorpen = 1;
public static int heroarmor = 1;
public static int herohealth = 5;
public static String inputstat;
public static int herothepoints = 0;
Hero(int points){
spendpoint(points);
}
public void attack(){
}
public void die(){
System.exit(0);
}
public void winbattle(){
System.out.println("You win the battle and have one new point to spend!");
spendpoint(1);
new NewEncounter();
}
public void levelup(){
System.out.println("You have leveled up and receive 5 new points to spend");
spendpoint(5);
new NewEncounter();
}
public void spendpoint(int points){
for(int x=0; x<points; x++){
System.out.println("Available Points: " + points);
System.out.println("Available Attributes:");
System.out.println("attack: " + heroattack);
System.out.println("speed: " + herospeed);
System.out.println("armorpen: " + heroarmorpen);
System.out.println("armor: " + heroarmor);
System.out.println("health: " + herohealth);
System.out.println(points);
System.out.println(x);
Scanner keyboard = new Scanner( System.in );
inputstat = keyboard.next( );
if(inputstat.equals("attack")){
heroattack = heroattack + 1;
}
else if(inputstat.equals("speed")){
herospeed = herospeed + 1;
}
else if(inputstat.equals("armorpen")){
heroarmorpen = heroarmorpen + 1;
}
else if(inputstat.equals("armor")){
heroarmor = heroarmor + 1;
}
else if(inputstat.equals("health")){
herohealth = herohealth + 5;
}
else{
System.out.println("Please pick one of the stats");
x = x-1;
}
}
}
}
public class StartGame {
StartGame(){ //runs through output for a new game
System.out.println("Welcome to the game");
System.out.println("Pick your hero's starting stats");
Hero thishero = new Hero(10); //spends your points
System.out.println("Let's Begin!/n/n");
new NewEncounter(); //goes into the encounter loops
}
}
at this point I I try to program an encounter in the NewEncounter class, but that isn't possible because I can't use that instance of my hero that I created. and I am pretty sure that my design is bad in the first place, I think I have read that you should be trying to use static variables as little as possible in the first place. I am still reading trying to grasp this but I have read a lot and I feel like nothing is helping me. I actually think a more "hands on" large scale project/tutorial might help me, but I don't know one. Anyways thanks for any help and sorry for the long/blog-like post.
The standard way to use an instance of one class within another is to either store a reference to it or to pass it into the method that stores or uses it.
For example:
class Encounter {
private final Hero mainHero;
private final List<Hero> participants;
public Encounter(Hero mainHero) {
this.mainHero = mainHero;
participants = new ArrayList<>();
}
public void addParticipant(Hero hero) {
participants.add(hero);
}
}
Allows:
Encounter encounter = new Encounter(hero);
or:
encounter.addParticipant(hero);
These can then be used within the class. For example:
class Encounter {
public void moveAllParticipants() {
participants.forEach(Hero::move);
}
}
I notice you have used a lot of public static class variables. This is unusual and there are few good reasons to use them. One is to define constants. If that's your intent then I suggest you use the following standard form:
private static final int HERO_ATTACK = 1;
If you intend for these to be instance variables (i.e. different for each hero) then they should not be static nor public.
This is the sort of area that is well covered in the various Java tutorials. I suggest working through one of them and coming back here if you have further issues.

non-static method move(int,int) cannot be referenced from a static context [duplicate]

This question already has answers here:
What is the reason behind "non-static method cannot be referenced from a static context"? [duplicate]
(13 answers)
Closed 9 years ago.
When i try to use the move i.e. Slide.move(1,0) i get the error: non-static method move(int,int) cannot be referenced from a static context
This is my code at the moment, which i have no idea whats wrong.
public void move(int row, int col) {
char [][] temp= new char [cells.length][];
for (int i= 0; i< cells.length; i++) {
int destRow = (i+row)%cells.length;
temp[destRow] = new char [cells[i].length];
for (int j= 0; j < cells[i].length; j++)
temp[destRow][(j+col)%cells[i].length] = cells[i][j];
}
cells= temp;
}
}
The error means exactly what it says.
Your move method is not static. It requires an instance of an object to be called, e.g.:
Slide s = new Slide();
s.move(...);
You are calling it, as it says, from a static context, i.e. a place with no this, perhaps another static method or directly via Slide.move(...). You will need to not do that.
These fail:
Slide.move(...); // error: move requires an instance
// and
class Slide {
void move (...) {
...
}
static void method () {
move(...); // error: method is static, there is no instance
}
}
These do not fail:
Slide s = new Slide();
s.move(...);
// or
class Slide {
void move (...) {
...
}
void method () {
move(...);
}
}
// or
class Slide {
static void move (...) {
...
}
static void method () {
move(...);
}
}
So either call it from a non-static context, or make it a static method.
As for recommending somewhere to read more about these things (which you asked in a comment), try the official Java tutorial at http://docs.oracle.com/javase/tutorial/ (take a look at the "Learning the Java Language" trail (in particular: http://docs.oracle.com/javase/tutorial/java/javaOO/classvars.html).
As for your output problems, since that's a separate question, you'd want to post a separate question for it.
Well that is because you defined the move method as a non-static method by saying public void to make it static you need to write public static void instead.
Also be aware that variable names are case sensitive, if you write Slide.move() you clearly call upon your Slide class because your variable was named slide.

error on calling static method from void java

Need help on calling a method from main class.
I need to call a method, thus I made an object to handle it.
below I quote my main method
public static void main(String[] args) {
// TODO code application logic here
SLRatio sl= new SLRatio();
sl.clustering(apa);
}
and here's the method I need to call
public class SLRatio {
public static String [][]clustering(String[][]apa) {
System.out.println("Cluster 1");
int a = apa.length/3;
String [][] cluster1=new String [a][apa[0].length];
for (int i =0; i<a; i++) {
for (int j=0;j<apa[0].length;j++) {
cluster1 [i][j] = apa[i][j];
}
}
for (int b = 0; b < cluster1.length; b++) {
for (int c = 0; c < cluster1[0].length; c++) {
System.out.print(cluster1[b][c] + "\t");
}
System.out.println("");
}
System.out.println("\n");
return cluster1;
}
}
and I got error message:
"Cannot find symbol,Accessing static method clustering"
What can I do to solve it? I have tried to change the syntax but it didn't work.
Thank you so much.
you didn't define method Allocation() in SLRatio
Note: static method should be called with classname (to avoid confision between instance method and static)
If it is static method, you don't need to call it through instance.
SLRatio .clustering(...);
should be enough.
And it seems you forgot to implement Allocation method.
Another suggestion, java naming convention, method name starts with small case letters.
Do not use static unless you are sure it is appropriate.
This is a popular programming error, partially because eclipse keeps on suggesting to make variables and methods static when they cannot be accessed. But usually, this is not the correct solution. While it fixes the compilation problem, it often breaks the application logic.
Right now, your problem probably is that apa has type String[][], but you are passing a String[] parameter to it. So it cannot be compiled, because there is no method clustering(String[] args).
Seriously, you need to learn more Java basics. Maybe from a book.

Categories

Resources