I am new to Java and really like the challenge. Currently I'm trying to build a game that contains 3 classes (Warrior, Mage, Rouge) which the player can choose from. Therefore I created a constructor for the Basics (Health, Mana, Stamina) and subclasses for Warrior, Mage and Rouge.
I'd like to print the choice for the player, but unfortunately it won't work. Maybe someone can show me the right way.
This is the super class. Don't get confused by the german notations. :D
public class Klassen {
String Klasse;
int Vitalitat; //Health
int Mana;
int Ausdauer; //Stamina
Klassen(String k, int v, int m, int a) {
Klasse = k;
Vitalitat = v;
Mana = m;
Ausdauer = a;
}
String getKlasse() {return Klasse;} //choice of classes
int getVit() {return Vitalitat;}
int getMana() {return Mana;}
int getAusdauer() {return Ausdauer;}
void setVit(int v) {Vitalitat =v;}
void setMana(int m) {Mana = m;}
void setAusdauer(int a) {Ausdauer = a;}
void setKlase(String k) {Klasse = k;}
void showBasic() {
System.out.println("Vitalitaet: " + Vitalitat);
System.out.println("Mana: " + Mana);
System.out.println("Ausdauer " + Ausdauer);
}
Here an example of a subclass :
public class Krieger extends Klassen {
int Starke;
Krieger(int v, int m, int a, int s) {
super("Krieger", v, m, a);
Starke = s;
}
int getStarke() {return Starke;}
void setStarke(int s) {Starke = s;}
void showStarke() {
System.out.println("Starke: " + Starke);
}
}
The next step is to create an array to hold all the three choices:
Klassen[] fillKlassen() { //filling the array
Klassen[] Auswahl = new Klassen[3];
Auswahl[0] = new Krieger(0,0,0,0); //Warrior
Auswahl[1] = new Magier(0,0,0,0); //Mage
Auswahl[2] = new Waldlaufer(0,0,0,0); //Rouge
return Auswahl;
}
The last step should be to create a method that prints the content of the arrays.
I guess something similar to:
class KlassenAuswahl {
Klassen[] fillKlassen() {
Klassen[] Auswahl = new Klassen[3];
Auswahl[0] = new Krieger(0,0,0,0); // Eclipse can't use that reference and wants me to change it to Klassen(int,int,int)
Auswahl[1] = new Magier(0,0,0,0);
Auswahl[2] = new Waldlaufer(0,0,0,0);
return Auswahl;
}
void showKlassen() {
for(int i = 0; i < fillKlassen().length; i++) {
System.out.println(fillKlassen()[i].getKlasse());
}
}
The main goal is to implement this method in my main() Method but this won't work properly. Can someone help me out?
Edit: The main problem seems to be that I get a nullpointer.exception. This may a result of an empty array I guess? The next thing is that I can't implement the showAuswahl() in my main() perhaps because its inside in the constructor class. Therefore I need to create a new class outside of it. But outside of the constructor I can't use my subclasses...
Cheers
namelessshameless
I got the solution. Needed to change my subclasses to static :)
Related
I have written the instructions below and till now, I've came up with having two parameters and letting the method to assign the value and retrieving it. However, one of the instruction I had to follow was to include one constructor with no parameters, so I'm wondering what statement should I make inside the constructor without any parameters. It would be wonderful if anyone gives be a instruction. This is the code I've came up so far.
public class Rectangle {
//first constructor no parameters
//public<class name> (<parameters>)<statements>}
//two parameters one for length, one for width
//member variables store the length and the width
//member methods assign and retrieve the length and width
//returning the area and perimeter
static int recPerimeter(int l, int w) {
return 2*(l+w);
}
static int recArea(int l, int w) {
return l*w;
}
public static void main(String[] args) {
int p = recPerimeter(5, 3);
System.out.println("Perimeter of the rectangle : " + p);
int a = recArea(5,3);
System.out.println("Area of the rectangle : " + a);
}
}
First off, I would take some time to read the java tutorials. At least the "Covering the Basics"
There is a ton wrong with your example. You should store the the attributes of a rectangle - width and length as data members of the class which will get initialized with values through the constructors. If a default constructor is called with no values, then set the attributes to whatever you want. I set them to zero in the example.
Also, you need to normally create an instance of your class and then access it. Big red flag if you are having to prepend "static" to everything.
public class Rectangle {
private int recLength;
private int recWidth;
public Rectangle() {
recLength = 0;
recWidth = 0;
}
public Rectangle( int l, int w ) {
recLength = l;
recWidth = w;
}
public int calcPerimeter() {
return 2*(recLength+recWidth);
}
public int calcArea() {
return recLength*recWidth;
}
public static void main (String [] args) {
Rectangle rec = new Rectangle(5,3);
System.out.println("Perimeter = "+ rec.calcPerimeter());
System.out.println("area = " + rec.calcArea());
}
}
Final(?) edit:
Leonardo Pina's solution looks like what I needed. Thank you all for your input! My code is now:
public final class Roll {
private static final Random r1 = new Random();
private final int r = level();
private static final int level() {
int s = 1, e = 100;
int r = r1.nextInt((e - s) + 1) + s;
return r;
}
public int itemType() {
boolean b = r1.nextBoolean();
int a = ((b) ? 1 : 2);
return a;
}
public int getR() {
return r;
}
}
And the implementation in the other class:
public class Damage {
Roll r;
Damage(Roll r) {
this.r = r;
}
public int damageOut() {
int a = r.getR(); //roll value
return a * 2; //test math on r
}
}
Edit:
Thank you for the responses. However, it seems my use of this method was not clear. Apologies! This is what I need:
Call Roll class, get e.g. "12"
OtherClass1 receives "12" from Roll via getter
OtherClass2 also receives "12" from Roll via getter
Call Roll class again, get a new random number, e.g. "48"
OtherClass1 receives "48" from Roll via getter
OtherClass2 also receives "48" from Roll via getter
Using the solutions provided, Roll creates a single random number and never creates a new one again. I need Roll to create random numbers on demand, and then share that random number with other classes. I do not want it to only generate one number and then stop. I hope this makes sense. Thank you for the responses so far!
I have searched for and read the other threads of a similar topic (including this one, which is how I tried to solve my problem), but the methods I have tried have failed. I need to create a single random value and then use that same value across multiple classes.
My random class:
public final class Roll {
private static final Random r1 = new Random();
private final int r = level();
private static final int level() {
int s = 1, e = 100;
int r = r1.nextInt((e - s) + 1) + s;
return r;
}
public int itemType() {
boolean b = r1.nextBoolean();
int a = ((b) ? 1 : 2);
return a;
}
public int getR() {
return r;
}
}
And a class where I call for the static value from the random class:
public class OtherClass{
Roll roll = new Roll();
int r = roll.getR();
public int getR() {
return r;
}
}
When I call the getter from OtherClass, the value is different than the getter from Roll. I would expect them to be the same value.
I call the values for testing like so:
Roll roll = new Roll();
int r = roll.getR();
OtherClass other = new OtherClass();
int o = other.getR();
Any guidance would be greatly appreciated. Have a good day.
When you create a new instance of OtherClass you also create a new instance of Roll, therefore, the rolls are different.
You need to make sure you are getting the value R from the same object Roll.
This could be achieved by using a singleton pattern for the Roll class, or you could specify the Roll object you want to use to get values, this way you could have several rolls for different purposes. i.e.
Edit:
Answering your edit: to get a new number, you should update the value of r in the Roll class whenever you generate a new value, for example, instead of returning a value, the level() method could update the r variable:
public final class Roll {
private static final Random r1 = new Random();
// We now attribute a value to r uppon construction
private final int r;
public Roll() {
level();
}
// Whenever level() is called the value of r is updated
private static final int level() {
int s = 1, e = 100;
int r = r1.nextInt((e - s) + 1) + s;
this.r = r;
}
public int itemType() {
boolean b = r1.nextBoolean();
int a = ((b) ? 1 : 2);
return a;
}
public int getR() {
return r;
}
}
class Game {
public static void main(String[] args) {
// Create the Roll obj
Roll myRoll = new Roll();
// Initialize the other objs with myRoll
Board board = new Board(myRoll);
Player player = new Player(myRoll);
// Do your comparison
int b = board.getRoll();
int p = player.getRoll();
// EDIT: get a new value
myRoll.level();
// Do your comparison once more
b = board.getRoll();
p = player.getRoll();
}
class Board {
Roll r;
Board(Roll roll) {
this.r = roll;
}
public int getRoll() {
return r.getR();
}
}
class Player {
Roll r;
Player(Roll roll) {
this.r = roll;
}
public int getRoll() {
return r.getR();
}
}
}
Probably the simplest way to make it work would be to field r in class Roll as static, so that the Roll class looks like this:
ublic final class Roll {
private static final Random r1 = new Random();
private static final int r = level();
private static final int level() {
int s = 1, e = 100;
int r = r1.nextInt((e - s) + 1) + s;
return r;
}
public int itemType() {
boolean b = r1.nextBoolean();
int a = ((b) ? 1 : 2);
return a;
}
public int getR() {
return r;
}
}
Or second approach would be to make Roll class a singleton.
Edit:
Since you have changed the intent of the question, and from what I understand you should look into Observer design pattern. It may be helpful for your case.
As someone said in the comments, you should follow the singleton design pattern, meaning that your variable r should be unique across all Roll class instances. To do this, your code will have to look something like this:
public class RandomTest {
public static void main(String[] args) {
Roll roll = new Roll();
int r = roll.getR();
OtherClass other = new OtherClass();
int o = other.getR();
}
}
class Roll {
private static Random r1 = new Random();
private static int r = level();
private static final int level() {
int s = 1, e = 100;
int r = r1.nextInt((e - s) + 1) + s;
return r;
}
public int itemType() {
boolean b = r1.nextBoolean();
int a = ((b) ? 1 : 2);
return a;
}
public int getR() {
return r;
}
}
class OtherClass{
Roll roll = new Roll();
int r = roll.getR();
public int getR() {
return r;
}
}
How about sharing the Roll instance?
Roll roll = new Roll();
// roll.roll(); // Unclear how you "refresh" the data
int r = roll.getR();
OtherClass other = new OtherClass(roll);
int o = other.getR();
assert(o == r);
class OtherClass {
private final Roll roll;
public OtherClass(Roll roll) {
this.roll = roll;
}
public int getR() {
return roll.getR();
}
}
Tip: I think a Dice class with a roll() method makes more sense.
I've looked all over the internet, but I can't figure out what I'm doing wrong. I'm trying my hand at using private variables from another class using get/set methods. Something's going wrong, but I can't figure it out.
public class Character
{
private int atk = 0;
private int def = 0;
private int spd = 0;
public void setStat(String stat, int n)
{
stat = stat.toLowerCase();
if(stat.equals("def") || stat.equals("defence") || stat.equals("defense"))
{
def = n;
}
if(stat.equals("atk") || stat.equals("attack"))
{
atk = n;
}
if(stat.equals("spd") || stat.equals("speed"))
{
spd = n;
}
}
public int getStat(String stat)
{
stat = stat.toLowerCase();
int n = -1;
if(stat.equals("def") || stat.equals("defence") || stat.equals("defense"))
{
n = def;
}
if(stat.equals("atk") || stat.equals("attack"))
{
n = atk;
}
if(stat.equals("spd") || stat.equals("speed"))
{
n = spd;
}
return n;
}
public Character(int a, int d, int c)
{
atk = a;
def = d;
spd = c;
}
}
This is my first class, Character which will be used as the template for the object, complete with get/set methods.
public class newCharacters
{
Character person1 = new Character(2, 4, 3);
person1.getStat("atk");
}
This is my second class, which constructs a character object and then tries to get a variable. Problem is, whenever I compile, it says that the object method needs an identifier. Exact quote: <identifier> expected
I can't figure out what it means, or what I'm doing wrong? I made get/set methods for each class, created the object in both classes, even constructed and called the object method within the Character class. Same problem every time. Can someone help?
public class newCharacters
{
Character person1 = new Character(2, 4, 3);
person1.getStat("atk");
}
This should not be in a class. This does not mean anything. A class can have bunch of instance variables and methods.
Please study the basics well ;)
Put it in a main method inside the Character class
public static void main(String [] args) {
Character person1 = new Character(2, 4, 3);
person1.getStat("atk");
}
public class NewCharacters
{
public static void main(String[] args) {
Character person1 = new Character(2, 4, 3);
person1.getStat("atk");
}
}
A program starts a main method like above.
Inside a class, at the top level only fields and methods may be declared (and constructors and initializer blocks, and other classes).
I have read up on Java Interfaces (callbacks) because I was told by a professor I should use callbacks in one of my programs. In my code, there are two Mathematical functions I can 'pick' from. Instead of making a method activate() and changing the code inside (from one function to the other) when I want to change functions, he said I should use callbacks. However, from what I've read about callbacks, I'm not sure how this would be useful.
EDIT: added my code
public interface
//the Interface
Activation {
double activate(Object anObject);
}
//one of the methods
public void sigmoid(double x)
{
1 / (1 + Math.exp(-x));
}
//other method
public void htan(final double[] x, final int start,
final int size) {
for (int i = start; i < start + size; i++) {
x[i] = Math.tanh(x[i]);
}
}
public double derivativeFunction(final double x) {
return (1.0 - x * x);
}
}
If you want to use interfaces something like this would work.
I have a MathFunc interface that has a calc method.
In the program I have a MathFunc for mutliplication and one for addition.
With the method chooseFunc you can choose one of both and with doCalc the current chosen MathFunc will do the calculation.
public interface MathFunc {
int calc(int a, int b);
}
and you can use it like that:
public class Program {
private MathFunc mult = new MathFunc() {
public int calc(int a, int b) {
return a*b;
}
};
private MathFunc add = new MathFunc() {
public int calc(int a, int b) {
return a+b;
}
};
private MathFunc current = null;
// Here you choose the function
// It doesnt matter in which way you choose the function.
public void chooseFunc(String func) {
if ("mult".equals(func))
current = mult;
if ("add".equals(func))
current = add;
}
// here you calculate with the chosen function
public int doCalc(int a, int b) {
if (current != null)
return current.calc(a, b);
return 0;
}
public static void main(String[] args) {
Program program = new Program();
program.chooseFunc("mult");
System.out.println(program.doCalc(3, 3)); // prints 9
program.chooseFunc("add");
System.out.println(program.doCalc(3, 3)); // prints 6
}
}
Can we swap two numbers in Java using pass by reference or call by reference?
Recently when I came across swapping two numbers in Java I wrote
class Swap{
int a,b;
void getNos(){
System.out.println("input nos");
a = scan.nextInt();
b = scan.nextInt(); // where scan is object of scanner class
}
void swap(){
int temp;
temp = this.a;
this.a = thisb;
this.b = this.a;
}
}
In the main method I call the above mentioned methods and take two integers a,b and then using the second method I swap the two numbers, but relative to the object itself....
Does this program or logic come under pass by reference?
And is this correct solution?
Yes and no. Java never passes by reference, and your way is one workaround. But yet you create a class just to swap two integers. Instead, you can create an int wrapper and use pass it, this way the integer may be separated when not needed:
public class IntWrapper {
public int value;
}
// Somewhere else
public void swap(IntWrapper a, IntWrapper b) {
int temp = a.value;
a.value = b.value;
b.value = temp;
}
As the comments show, I might not have been clear enough, so let me elaborate a little bit.
What does passing by reference mean? It means that when you pass an argument to the method, you can change the original argument itself inside this method.
For example, if Java was pass-by-reference, the following code will print out x = 1:
public class Example {
private static void bar(int y) {
y = 10;
}
public static void main(String[] args) {
int x = 1;
bar(x);
System.out.println("x = " + x);
}
}
But as we know, it prints 0, since the argument passed to the bar method is a copy of the original x, and any assignment to it will not affect x.
The same goes with the following C program:
static void bar(int y) {
y = 1;
}
int main(int argc, char * argc[]) {
int x = 0;
bar(x);
printf("x = %d\n", x);
}
If we want to change the value of x, we will have to pass its reference (address), as in the following example, but even in this case, we will not pass the actual reference, but a copy of the reference, and by dereferencing it we will be able to modify the actual value of x. Yet, direct assignment to the reference will no change the reference itself, as it is passed by value:
static void bar(int &y) {
*y = 1;
y = NULL;
}
int main(int argc, char * argc[]) {
int x = 0;
int * px = &x;
bar(px);
printf("x = %d\n", x); // now it will print 1
printf("px = %p\n", px); // this will still print the original address of x, not 0
}
So passing the address of the variable instead of the variable itself solves the problem in C. But in Java, since we don't have addresses, we need to wrap the variable when we want to assign to it. In case of only modifying the object, we don't have that problem, but again, if we want to assign to it, we have to wrap it, as in the first example. This apply not only for primitive, but also for objects, including those wrapper objects I've just mentioned. I will show it in one (longer) example:
public class Wrapper {
int value;
private static changeValue(Wrapper w) {
w.value = 1;
}
private static assignWrapper(Wrapper w) {
w = new Wrapper();
w.value = 2;
}
public static void main(String[] args) {
Wrapper wrapper = new Wrapper();
wrapper.value = 0;
changeValue(wrapper);
System.out.println("wrapper.value = " + wrapper.value);
// will print wrapper.value = 1
assignWrapper(w);
System.out.println("wrapper.value = " + wrapper.value);
// will still print wrapper.value = 1
}
}
Well, that's it, I hope I made it clear (and didn't make too much mistakes)
import java.util.*;
public class Main
{
int a,b;
void swap(Main ob)
{
int tmp=ob.a;
ob.a=ob.b;
ob.b=tmp;
}
void get()
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter a and b: ");
a=sc.nextInt();
b=sc.nextInt();
}
public static void main(String[] args) {
Main ob=new Main();
ob.get();
ob.swap(ob);
System.out.println(ob.a+" "+ob.b);
}}