Java Interfaces/Callbacks for Using 1 of 2 Possible Methods - java

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
}
}

Related

How do I solve Java '.class' expected error Java, compilation failed [duplicate]

This question already has an answer here:
What does "error: '.class' expected" mean and how do I fix it
(1 answer)
Closed 4 months ago.
I was trying to create a java program that adds 2 numbers but keep getting this error
error: '.class' expected
return int ad();
1 error
error: compilation failed
Here is my code
public class Sum {
int a;
int b;
int add;
public int ad(int a, int b){
int add = (int) a + b;
return add;
}
public static void main(String[] args) {
return int ad();
}
}
public class Sum {
/*
int a;
int b;
int add;
*/
public int ad(int a, int b) {
return a + b;
}
public static void main(String[] args) {
int sum = ad(1, 3);
System.out.println(sum);
}
}
main()'s return type is void - it cannot return anything. Mostly it is used to call functions.
Pass parameters to ad() - or you will get a compile time exception - it is expecting 2 integers.
Redundant casting here: int add = (int) a + b; - for a simple method like this, you can directly return a + b;
Unused variables - all your member variables are unused.
Solution 2 (using member variables):
public class Sum {
private int a;
private int b;
private int ad() {
return a + b;
}
public static void main(String[] args) {
Sum s = new Sum();
s.a = 1;
s.b = 2;
int sum = s.ad();
System.out.println(sum);
}
}
There are some points in your code:
main() can't return anything because it's a void method.
You don't have to use member variables in this situation. Member variables are most used in classes. Like for instance when you want to create a Person class.
You don't have to type int add = (int) a + b because you don't have to convert anything.The datatype is already an int.
Here's an example of what you can do:
public class Main {
public int add(int a, int b){
int result = a + b;
return result;
}
public static void main(String[] args) {
Main main = new Main();
System.out.println(main.add(1, 1));
}
}
Output:
2
Hope this information was useful!
The method "public static void main(String[] args)" is static and the method "public public int ad(int a, int b)" is non-static.
If you want to reach the method "public int ad(int a, int b)" then make an instance of class Sum and call the method "ad(int a, int b)", or make the method "ad(int a, int b)" static. As already mentioned in comments above, "public static void main(String[] args)" has no return type - it is void, so no "return int ad()" in main method is needed.
Alrernative 1 - Make an instance of class Sum and call method ad(int a, int b):
public class Sum {
int a;
int b;
int add;
public int ad(int a, int b) {
int add = (int) a + b;
return add;
}
public static void main(String[] args) {
Sum sum = new Sum(); // Make an instance of class Sum
int result = sum.ad(1, 2); // and call method ad
System.out.println("Result: " + result); // Output: 'Result: 3'
}
}
Alternative 2 - Make method ad(int a, int b) static:
public class Sum {
public static int ad(int a, int b) { // Make method ad static
int add = (int) a + b;
return add;
}
public static void main(String[] args) {
int result = Sum.ad(1, 3); // Calling static method ad
System.out.println("Result: " + result); // Output: 'Result: 3'
}
}
Read more about diffrence between static and non-static methods here:
https://stackoverflow.com/questions/3903537/what-is-the-difference-between-a-static-method-and-a-non-static-method#:~:text=A%20static%20method%20belongs%20to%20the%20class%20and%20a%20non,class%20that%20it%20belongs%20to.&text=In%20the%20other%20case%2C%20a,class%20has%20already%20been%20instantiated.

Show the content of a subclass

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 :)

Why I can't declare and run method in main method of Java class [duplicate]

This question already has answers here:
Nested functions in Java
(8 answers)
Closed 6 years ago.
Probably I missed something during checking Java core, but please help me to understand why I cannot use method declared in java main method which is commented
class R {
public int cal(int a, int b) {
return a + b;
}
public int cal3(int a, int b) {
return a * b;
}
}
public class Rect {
public static void main(String arg[]) {
/*public static int cal2 ( int a, int b){
return a + b;
}
int ab2 = cal2(2,2);
System.out.println(ab2);*/
R r = new R();
int ab = r.cal(2, 2);
System.out.println(ab);
int ab3 =r.cal3(2,3);
System.out.println(ab3);
}
}
You cannot declare a method inside another method.
public static int cal2 ( int a, int b){
return a + b;
}
public static void main(String arg[]) {
int ab2 = cal2(2);
System.out.println(ab2);
R r = new R();
int ab = r.cal(2, 2);
System.out.println(ab);
int ab3 =r.cal3(2,3);
System.out.println(ab3);
}
As others have stated, it is true that you cannot have a typical method defined inside another. But, for clarity, there is an equivalent (Java8 - if that still needs to be stated these days) using the BiFunction interface. For example,
public static void main(String[] args) {
BiFunction<Integer, Integer, Integer> func = (a, b) -> a + b;
System.out.println(func.apply(3, 4));
}

Why am I getting a "; expected" error?

public class homework
{
public static void intPow(int a, int b)
{
Math.pow(a,b);
}
public static void main(String args[])
{
intPow();
}
}
I'm trying to learn how to create a method, but I keep getting 10 ; expected errors. I know this code isn't correct, but I can't seem to find how to create a method correctly. In this case I'm trying to create a method that returns a^b.
You need to pass two int parameters into intPow():
public static void main(String args[])
{
int a = 2;
int b = 5;
intPow(a, b); //32
}
Furthermore, you should probably return an int from intPow() so you can play with it later:
public static int intPow(int a, int b) {
return Math.pow(a, b);
}
Then in main():
public static void main(String args[])
{
int a = 2;
int b = 5;
int power = intPow(a, b); //32
System.out.println(power);
}
pass two int values in intPow();
intPow(5,5);
And anyways the value would not be printed.
You need to use System.out.println() to print it.
Change
intPow();
to
intPow(2,3); // or any number
You declare intPow as a function that takes two parameters. But when you call it from main, you dont pass any. To fix this, change this line in main -
intPow();
to
intPow(1, 2);//or whatever other numbers you want.
public class homework
{
public static int intPow(int a, int b)
{
return Math.pow(a,b);
}
public static void main(String args[])
{
int a = 3;
int b = 4;
int result = intPow(a, b);
System.out.println(result);
}
}
If the goal is to create a method that returns a^b, the method should return a value. You probly need to convert to int though, because Math.pow works with doubles.
public static int intPow(int a, int b) {
return (int) Math.pow(a,b);
}
then call it using two parameters for a and b:
int result = intPow( 2, 3 );

How do this subclass interact with the main class

I'm stuck on a mock exam question. I created a class called Power which allowed a number to be raised to any power.
The third part of the question asks me to create another class BoundedPower which would extend Power. I was given the MAX-X variable (x cannot exceed this value) and told that the BoundedPower class must: behave like the Power class, use a constructor and use thepowN method.
My code is below, i am not sure what to do to make the BoundedPower class work.
public class Power {
private double x = 0;
Power(double x) {
this.x = x;
}
public double getX() {
return x;
}
public double powN(int n) {
double result = 1.0;
for (int i = 0; i < n; i++) {
result = result * x;
}
return result;
}
public static void main(String[] args) {
Power p = new Power(5.0);
double d = p.powN(3);
System.out.println(d);
}
}
public class BoundedPower extends Power {
public static final double MAX_X = 1000000;
// invariant: x <= MAX_X
Power x;
BoundedPower(double x) {
super(x);
// this.x=x; x is private in Power class
}
public double powN(int n) {
if (x.getX() > MAX_X) {
return 0;
} else {
double result = 1.0;
for (int i = 0; i < n; i++) {
result = result * getX();
}
return result;
}
}
public static void main(String[] args) {
BoundedPower bp = new BoundedPower(5);
double test = bp.powN(4);
System.out.println(test);
}
}
There is no need for that instance Power variable x in your class. Any BoundedPower instance IS a Power instance, and as such, to reference a method from Power, do super.blah(), so for x.getX(), do super.getX()
Also, in your comments, you said this.x=x fails because its private. When you do the super call, it calls the constructor of the superclass (Power), which sets x there, so there is no need for this.x=x
public class BoundedPower extends Power {
public static final double MAX_X = 1000000;
BoundedPower(double x) {
super(x);
}
public double powN(int n) {
if (x.getX() > MAX_X) {
return 0;
} else {
return super.powN(n);
}
}
public static void main(String[] args) {
BoundedPower bp = new BoundedPower(5);
double test = bp.powN(4);
System.out.println(test);
}
}
You don't have to copy your computation formular to the subclass (just call super.powN(..)). You also don't need another instance of Power within BoundedPower.
This is probably what they had in mind:
public class Power {
public double powN(double x, int n) {
double result = 1.0;
for (int i = 0; i < n; i++) {
result = result * x;
}
return result;
}
}
public class BoundedPower extends Power {
private final double maxX;
public BoundedPower(double maxX) {
this.maxX = maxX;
}
public double powN(double x, int n) {
if (x > maxX) {
throw new IllegalArgumentException("x value [" + x + "] " +
"greater than expected max [" + maxX + "]");
}
return super.powN(x, n);
}
}
I would do it in a different way. From what you're saying the BoundedPower class makes sense only for a bounded x (up to MAX_X).
Consequently, I would not allow the creation of an object with an x greater than MAX_X (i.e. a BoundedPower object cannot exist for unbounded x's)
So the implementation would be exactly as the the Power implementation excepting the way you build BoundedPower instances : you first check whether it makes sense to build it
public class BoundedPower extends Power {
private static final double MAX_X = 1000000; //makes no sense to be public
public static BoundedPower newBoundedPower(int n)
throws IllegalNumberException{
if(x > MAX_X) throw new IllegalNumberException();
return new BoundedPower(x);
}
private BoundedPower(double x) {
super(x);
}
}

Categories