Hi i am trying to solve the problem I am facing
public class exam {
public static void main(String[] args) {
test1 a = new test1();
}
int zahl(int x, int y) {
int e;
if(x>y) {
e=x-y;
}else {
e=y-x;
}
if(e==0) {
return 0;
}
int z=0;
int i=1;
while(i<=e) {
z=z+i;
i++;
}
return z;
}
}
what I want to do is to call the zahl method to the test1 class
public class test1{
private exam b;
public void init() {
b = new exam();
}
void test() {
int result = b.zahl(2, 2);
assertEquals(1, result);
}
}
this is what I have tried, but it returns nothing, even though it's supposed to show me error.
You should probably be declaring your functions with the public tag i.e. public void test() if you intend to access them from other functions outside of that package. The usual Class naming convention in Java is with capital first letter, which makes your code more readable for you and others.
For your question, I don't think you are actually invoking the test() method of the test1 class. If you want that method to get called every time, you could place it inside the default Constructor.
I have three classes for now one is the main class,
Class A:
class A{
int result;
int getHeightBase() {
return result;
}
void setHeightBase(int h, int b) {
result=h*b;
}
}
Class B:
This class will perform different calculations than A
class B{
int result;
int getHeightBase() {
return result;
}
void setHeightBase(int h, int b) {
result=12*h*b;
}
}
MainClass:
public class Main {
public static void main(String[] args) {
A a= new A();
B b= new B();
calculateArea(a,b);
}
void calculateArea(A obj1, B obj2){
obj1.setHeightBase(5,6);
obj2.setHeightBase(5,6);
}
}
Now, when I change arguments of class A method setHeightBase or class B method setHeightBase for some reason I got to change in MainClass as well where I am sending integer values , and I think this opposes design patterns, could anyone please guide me how to get rid of this, I want to change arguments later on but I don't want to effect any other class or change any other class, I tried to use interface but did not get how to get rid of this problem
thanks a lot in advance , any help would be appreciated
Let's say you have this class:
public void printNumbers(int one, int two) {
int result = one + two;
System.out.println("result = " + result);
}
And this is being called from multiple other classes. You can't just change the signature (returntype, method name, parameterlist) and expect everything to work just fine.
Now, let's assume you don't want it to automatically print a sum, but you want to be able to choose what action to take addition or subtraction.
For the current method, don't change anything. It's been used for addition. So, you'll add an overloaded method, which accepts an additional parameter:
public void printNumbers(int one, int two) {
int result = one + two;
System.out.println("result = " + result);
}
public void printNumbers(int one, int two, String action) {
// action is either add or sub
if ( !"add".equals(action) && !"sub".equals(action) ) {
System.out.println("Error");
} else if ("add".equals(action) {
int result = one + two;
System.out.println("result = " + result);
} else {
int result = one - two;
System.out.println("result = " + result);
}
}
Once you did that, you can change the original method to:
public void printNumbers(int one, int two) {
printNumbers(one, two, "add");
}
public void printNumbers(int one, int two, String action) {
// action is either add or sub
if ( !"add".equals(action) && !"sub".equals(action) ) {
System.out.println("Error");
} else if ("add".equals(action) {
int result = one + two;
System.out.println("result = " + result);
} else {
int result = one - two;
System.out.println("result = " + result);
}
}
and the functionality that was once provided will remain the same, while you won't have to change any other existing code
You can use method overloading,
void setHeightBase(int h, int b) {
result=12*h*b;
}
void setHeightBase(double h, double b) {
result=12.0*h*b;
}
this will save the previous method and also creates a method with exact name and different arguments.
I would use an abstract class as the base and extend other classes from it. The public methods in the abstract class will act as the contract to the outside world. In future, if you want to expose other method you add them to the interface and depending on the functionality, you could provide a default implementation. In real world scenarios, you avoid changing an existing contract.
As an example, your classes can be written as such
abstract class Shape{
int height;
int base;
Shape(int height, int base){
super();
this.height = height;
this.base = base;
}
public int area(){
return height * base;
}
}
class Shape1 extends Shape{
Shape1(int height, int base){
super(height, base);
}
}
class Shape2 extends Shape{
Shape2(int height, int base){
super(height, base);
}
#Override
public int area(){
return 12 * height * base;
}
}
public class Test{
public static void main(String args[]){
Shape s1 = new Shape1(2,3);
Shape s2 = new Shape2(2,3);
System.out.println(s1.area());
System.out.println(s2.area());
}
}
I have two types of objects that can perform a calculate() operation with either an int or a byte:
public class A {
public int calculate(int n) {...}
}
and
public class B {
public byte calculate(byte n) {...}
}
I want to have an ArrayList of objects that I can loop over calling the calculate method.
How do I do that, using an interface?
Considering the difference in the int/byte signature
Would something like this be a good approach?
public interface Calculatable {
int calculate(int number);
default byte calculate(byte number) {
return (byte) calculate((int) number);
}
}
Maybe using a 3-rd class and check based on type could be useful
public class TestCalc {
public static void main(String[] args) {
List<Object> l = new ArrayList<Object>();
l.add(Integer.valueOf(300));
l.add(Byte.valueOf("120"));
l.add(Integer.valueOf(1));
TestCalc tc = new TestCalc();
ComputeAB cab = tc.new ComputeAB();
for (Object o : l) {
System.out.println(cab.calculate(o) + ":" + cab.type);
}
}
class A {
public int calculate(int n) {
return n;
}
}
class B {
public byte calculate(byte n) {
return n;
}
}
class ComputeAB {
String type = "";
public Object calculate(Object o) {
if (o instanceof Integer) {
type = "int";
return new A().calculate((int) o);
}
type = "byte";
return new B().calculate((byte) o);
}
}
}
Output
300:int
120:byte
1:int
Could you point me to the JLS section where it is specified that inherited methods will not act on subclasses re-defined variables?
I.e. the output of the following code is "value is 3" and not "value is 5".
public class PlayGround {
int value = 3;
public int getValue() {
return value;
}
public static void main(String[] args) {
PlayGround.PlayGroundSon pg = new PlayGround().new PlayGroundSon();
System.out.println("value is "+pg.getValue());
}
class PlayGroundSon extends PlayGround{
int value = 5;
}
}
You have not "re-defined" value. You have created a completely separate field in PlayGroundSon that happens to have the same name.
You can only override methods. If you want the program to print 5 you will have to override the getValue() method. I have also changed the name of the variable in PlayGroundSon to emphasize that it is not the same as value in PlayGround.
public class PlayGround {
int value = 3;
public int getValue() {
return value;
}
public static void main(String[] args) {
PlayGround.PlayGroundSon pg = new PlayGround().new PlayGroundSon();
System.out.println("value is "+pg.getValue());
}
class PlayGroundSon extends PlayGround{
int sonValue = 5;
#Override
public int getValue() {
return sonValue;
}
}
}
I am trying to return 2 values from a Java method but I get these errors. Here is my code:
// Method code
public static int something(){
int number1 = 1;
int number2 = 2;
return number1, number2;
}
// Main method code
public static void main(String[] args) {
something();
System.out.println(number1 + number2);
}
Error:
Exception in thread "main" java.lang.RuntimeException: Uncompilable source code - missing return statement
at assignment.Main.something(Main.java:86)
at assignment.Main.main(Main.java:53)
Java Result: 1
Instead of returning an array that contains the two values or using a generic Pair class, consider creating a class that represents the result that you want to return, and return an instance of that class. Give the class a meaningful name. The benefits of this approach over using an array are type safety and it will make your program much easier to understand.
Note: A generic Pair class, as proposed in some of the other answers here, also gives you type safety, but doesn't convey what the result represents.
Example (which doesn't use really meaningful names):
final class MyResult {
private final int first;
private final int second;
public MyResult(int first, int second) {
this.first = first;
this.second = second;
}
public int getFirst() {
return first;
}
public int getSecond() {
return second;
}
}
// ...
public static MyResult something() {
int number1 = 1;
int number2 = 2;
return new MyResult(number1, number2);
}
public static void main(String[] args) {
MyResult result = something();
System.out.println(result.getFirst() + result.getSecond());
}
Java does not support multi-value returns. Return an array of values.
// Function code
public static int[] something(){
int number1 = 1;
int number2 = 2;
return new int[] {number1, number2};
}
// Main class code
public static void main(String[] args) {
int result[] = something();
System.out.println(result[0] + result[1]);
}
You could implement a generic Pair if you are sure that you just need to return two values:
public class Pair<U, V> {
/**
* The first element of this <code>Pair</code>
*/
private U first;
/**
* The second element of this <code>Pair</code>
*/
private V second;
/**
* Constructs a new <code>Pair</code> with the given values.
*
* #param first the first element
* #param second the second element
*/
public Pair(U first, V second) {
this.first = first;
this.second = second;
}
//getter for first and second
and then have the method return that Pair:
public Pair<Object, Object> getSomePair();
You can only return one value in Java, so the neatest way is like this:
return new Pair<Integer>(number1, number2);
Here's an updated version of your code:
public class Scratch
{
// Function code
public static Pair<Integer> something() {
int number1 = 1;
int number2 = 2;
return new Pair<Integer>(number1, number2);
}
// Main class code
public static void main(String[] args) {
Pair<Integer> pair = something();
System.out.println(pair.first() + pair.second());
}
}
class Pair<T> {
private final T m_first;
private final T m_second;
public Pair(T first, T second) {
m_first = first;
m_second = second;
}
public T first() {
return m_first;
}
public T second() {
return m_second;
}
}
Here is the really simple and short solution with SimpleEntry:
AbstractMap.Entry<String, Float> myTwoCents=new AbstractMap.SimpleEntry<>("maximum possible performance reached" , 99.9f);
String question=myTwoCents.getKey();
Float answer=myTwoCents.getValue();
Only uses Java built in functions and it comes with the type safty benefit.
Use a Pair/Tuple type object , you don't even need to create one if u depend on Apache commons-lang. Just use the Pair class.
you have to use collections to return more then one return values
in your case you write your code as
public static List something(){
List<Integer> list = new ArrayList<Integer>();
int number1 = 1;
int number2 = 2;
list.add(number1);
list.add(number2);
return list;
}
// Main class code
public static void main(String[] args) {
something();
List<Integer> numList = something();
}
public class Mulretun
{
public String name;;
public String location;
public String[] getExample()
{
String ar[] = new String[2];
ar[0]="siva";
ar[1]="dallas";
return ar; //returning two values at once
}
public static void main(String[] args)
{
Mulretun m=new Mulretun();
String ar[] =m.getExample();
int i;
for(i=0;i<ar.length;i++)
System.out.println("return values are: " + ar[i]);
}
}
o/p:
return values are: siva
return values are: dallas
I'm curious as to why nobody has come up with the more elegant callback solution. So instead of using a return type you use a handler passed into the method as an argument. The example below has the two contrasting approaches. I know which of the two is more elegant to me. :-)
public class DiceExample {
public interface Pair<T1, T2> {
T1 getLeft();
T2 getRight();
}
private Pair<Integer, Integer> rollDiceWithReturnType() {
double dice1 = (Math.random() * 6);
double dice2 = (Math.random() * 6);
return new Pair<Integer, Integer>() {
#Override
public Integer getLeft() {
return (int) Math.ceil(dice1);
}
#Override
public Integer getRight() {
return (int) Math.ceil(dice2);
}
};
}
#FunctionalInterface
public interface ResultHandler {
void handleDice(int ceil, int ceil2);
}
private void rollDiceWithResultHandler(ResultHandler resultHandler) {
double dice1 = (Math.random() * 6);
double dice2 = (Math.random() * 6);
resultHandler.handleDice((int) Math.ceil(dice1), (int) Math.ceil(dice2));
}
public static void main(String[] args) {
DiceExample object = new DiceExample();
Pair<Integer, Integer> result = object.rollDiceWithReturnType();
System.out.println("Dice 1: " + result.getLeft());
System.out.println("Dice 2: " + result.getRight());
object.rollDiceWithResultHandler((dice1, dice2) -> {
System.out.println("Dice 1: " + dice1);
System.out.println("Dice 2: " + dice2);
});
}
}
You don't need to create your own class to return two different values. Just use a HashMap like this:
private HashMap<Toy, GameLevel> getToyAndLevelOfSpatial(Spatial spatial)
{
Toy toyWithSpatial = firstValue;
GameLevel levelToyFound = secondValue;
HashMap<Toy,GameLevel> hm=new HashMap<>();
hm.put(toyWithSpatial, levelToyFound);
return hm;
}
private void findStuff()
{
HashMap<Toy, GameLevel> hm = getToyAndLevelOfSpatial(spatial);
Toy firstValue = hm.keySet().iterator().next();
GameLevel secondValue = hm.get(firstValue);
}
You even have the benefit of type safety.
Return an Array Of Objects
private static Object[] f ()
{
double x =1.0;
int y= 2 ;
return new Object[]{Double.valueOf(x),Integer.valueOf(y)};
}
In my opinion the best is to create a new class which constructor is the function you need, e.g.:
public class pairReturn{
//name your parameters:
public int sth1;
public double sth2;
public pairReturn(int param){
//place the code of your function, e.g.:
sth1=param*5;
sth2=param*10;
}
}
Then simply use the constructor as you would use the function:
pairReturn pR = new pairReturn(15);
and you can use pR.sth1, pR.sth2 as "2 results of the function"
You also can send in mutable objects as parameters, if you use methods to modify them then they will be modified when you return from the function. It won't work on stuff like Float, since it is immutable.
public class HelloWorld{
public static void main(String []args){
HelloWorld world = new HelloWorld();
world.run();
}
private class Dog
{
private String name;
public void setName(String s)
{
name = s;
}
public String getName() { return name;}
public Dog(String name)
{
setName(name);
}
}
public void run()
{
Dog newDog = new Dog("John");
nameThatDog(newDog);
System.out.println(newDog.getName());
}
public void nameThatDog(Dog dog)
{
dog.setName("Rutger");
}
}
The result is:
Rutger
You can create a record (available since Java 14) to return the values with type safety, naming and brevity.
public record MyResult(int number1, int number2) {
}
public static MyResult something() {
int number1 = 1;
int number2 = 2;
return new MyResult(number1, number2);
}
public static void main(String[] args) {
MyResult result = something();
System.out.println(result.number1() + result.number2());
}
First, it would be better if Java had tuples for returning multiple values.
Second, code the simplest possible Pair class, or use an array.
But, if you do need to return a pair, consider what concept it represents (starting with its field names, then class name) - and whether it plays a larger role than you thought, and if it would help your overall design to have an explicit abstraction for it. Maybe it's a code hint...
Please Note: I'm not dogmatically saying it will help, but just to look, to see if it does... or if it does not.