I've been trying to make a custom output from the constructor in Java, but it keeps giving me the location of it. The return does not work and throws up an error. The code is:
Public class Example {
public static int a, b;
Example(int inputForA, int inputForB){
a = inputForA;
b = inputForB;
}
}
The output i want is a/b (a fraction, for example 3/2). I tried a return command, but it does not work:
Public class Example {
public static int a, b;
Example(int inputForA, int inputForB){
a = inputForA;
b = inputForB;
return a "/" b; //i even tried making String Example(){...} in the beginning but it still does not work, throws an error
}
}
The output i'm getting, when i am trying to print Example (3, 2)System.out.println(Example(3, 2)) is Example@4dd8dc3 and as mentioned i need 3/2.
Is there a way to do it? Thanks!
CodePudding user response:
Example is a class, not a method. It's like a template for an object.
But you can put a method in that class that returns what you want.
Example.java
package myPackage;
public class Example
{
public static int a, b;
Example(int inputForA, int inputForB)
{
a = inputForA;
b = inputForB;
}
float compute ()
{
return (float)a/(float)b;
}
}//_Example
Now we create an instance of Example and use this object in another class.
Main.java
package myPackage;
public class Main
{
public static void main(String []args)
{
Example exp = new Example (3, 2);
System.out.println(exp.compute());
}//_main
}//_Main
