I'm trying to mock the class and call the methods using that, but for some reason the methods are not being initiated.
The class to be tested
public enum Square {
SQUARE_SET(3);
private final int a;
Square(int l) {
this.a = l*l;
}
public int getSquare() {
return a;
}//can not trigger this method
#Override
public String toString() {
StringBuilder sb = new StringBuilder("Area :");
sb.append(a);
return sb.toString();
}//can not trigger this method
}
My code for testing the above class
class SquareTest {
int l;
private int a;
#Test
void testGetSquare() {
Square Square = mock(Square.class);
assertEquals(a, Square.getSquare());
}
void testToString() {
Square Square = mock(Square.class);
StringBuilder sb = new StringBuilder("Area :");
sb.append(a);
sb.toString();
when(Square.toString()).thenReturn(sb.toString());
}
}
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.
I have a class which only allows integers with limited amount. The problem is, class is doing its work but when I use multiple objects, it only takes the last objects limitation number and applies to others.
I also couldn't get rid of static warnings.
Code is ;
public class LimitedIntegerTF extends JTextField {
private static final long serialVersionUID = 1L;
private static int limitInt;
public LimitedIntegerTF() {
super();
}
public LimitedIntegerTF(int limitInt) {
super();
setLimit(limitInt);
}
#SuppressWarnings("static-access")
public final void setLimit(int newVal)
{
this.limitInt = newVal;
}
public final int getLimit()
{
return limitInt;
}
#Override
protected Document createDefaultModel() {
return new UpperCaseDocument();
}
#SuppressWarnings("serial")
static class UpperCaseDocument extends PlainDocument {
#Override
public void insertString(int offset, String strWT, AttributeSet a)
throws BadLocationException {
if(offset < limitInt){
if (strWT == null) {
return;
}
char[] chars = strWT.toCharArray();
boolean check = true;
for (int i = 0; i < chars.length; i++) {
try {
Integer.parseInt(String.valueOf(chars[i]));
} catch (NumberFormatException exc) {
check = false;
break;
}
}
if (check)
super.insertString(offset, new String(chars),a);
}
}
}
}
How I call it on another class ;
final LimitedIntegerTF no1 = new LimitedIntegerTF(5);
final LimitedIntegerTF no2 = new LimitedIntegerTF(7);
final LimitedIntegerTF no3 = new LimitedIntegerTF(10);
The result is no1, no2, and no3 has (10) as a limitation.
Example:
no1: 1234567890 should be max len 12345
no2: 1234567890 should be max len 1234567
no3: 1234567890 it's okay
It's because your limitInt is static, which means it has the same value for all instances of that class (What does the 'static' keyword do in a class?). Make it non-static, and each instance of your class will have their own value for it.
If you want to use limitInt in the inner class UpperCaseDocument, then make that class non-static as well. However, if you do that, each instance of UpperCaseDocument will also have an instance of LimitedIntegerTF associated with it.
Suppose I am importing table entries, where a single entry can be stored in a class:
class Foo {
int i1;
int i2;
double d1;
}
After the import is complete, I will need to have access to the imported values themselves, as well as to their normalized versions. So far, I have implemented this functionality as follows:
class FooWithMaxTracking {
private int i1;
private static int i1_max=0;
public void setI1(int value){
this.i1 = value;
if (value > i1_max) { i1_max = value; }}
public int getI1(){
return i1;}
public double normI1(){
return i1/((double)i1_max);}
private int i2;
private static int i2_max=0;
public void setI2(int value){ <code identical to written above> }
public int getI2(){ ... }
public double normI2(){ ... }
// and another set of similar 2 variables & 3 functions for 'double d1'
}
In this implementation I strongly dislike the fact that I had to write the same code many times (only three in this example, but about ten times in the real project). Is there any way to make the code more DRY ("don't repeat yourself")?
If you do not mind a slight loss of performance, you can put all the maxima in a static Map, define a class that holds a getter, a setter, and a norm methods, and replace the individual variables with instances of that class:
private static Map<String,Object> max = new HashMap<String,Object>();
private static class IntMaxTrack {
private final String key;
private int value;
public IntMaxTrack(String k, int v) {
key = k;
value = v;
max.put(key, value);
}
public int get() { return value; }
public void set(int v) {
int m = ((Integer)max.get(key)).intValue();
value = v;
if (value > m) {
max.put(key, value);
}
}
public double norm() {
int m = ((Integer)max.get(key)).intValue();
return val / ((double)m);
}
}
Make a similar class for double, i.e. DblMaxTrack Now you can replace primitives with instances of these classes, and call their get, set, and norm from the corresponding methods of your class.
What about defining one class with the necessary code, like:
public class Bar {
private int i1;
private static int i1_max = 0;
public void setI1(int value) {
// ...
}
public int getI1() {
// ...
}
public double normI1() {
// ...
}
}
And using it sevearl times, like:
class FooWithMaxTracking {
one = new Bar();
two = new Bar();
three = new BarForDouble();
}
Needing to create an unspecified number of objects, I tried to create a builder that do that. All was well until I realized that my builder creates all objects with their properties having the same values.
So when I call the builder:
ValidationHelper v = new ValidationHelper.HelperBuilder()
.addHelper("ICAO Identifier", icaoIdentifier, rulesICAO)
.addHelper("Long Name", longName, rulesLongName)
.build();
... I'll have 2 objects and their properties will have values of the last object the builder was asked to create.
To start with, is factory builder the prudent approach to this? Secondly, is my builder salvageable?
Builder:
public class ValidationHelper {
private static ArrayList<HelperBuilder> validatorHelpers = new ArrayList();
public static class HelperBuilder {
private String txtFieldName;
private String txtFieldValue;
private List<Integer> valCodes = new ArrayList<Integer>();
private ArrayList<HelperBuilder> innerValidatorHelpers = new ArrayList<HelperBuilder>();
public HelperBuilder() {}
public final HelperBuilder addHelper(String txtFieldName, String txtFieldValue, int[] validationCodes) {
this.txtFieldName = txtFieldName;
this.txtFieldValue = txtFieldValue;
for( int i = 0; i < validationCodes.length; i++ ){
getValCodes().add((Integer) validationCodes[i]);
}
innerValidatorHelpers.add(this);
return this;
}
public final ValidationHelper build() {
return new ValidationHelper(this);
}
public String getTxtFieldName() {
return txtFieldName;
}
public String getTxtFieldValue() {
return txtFieldValue;
}
public List<Integer> getValCodes() {
return valCodes;
}
}//end HelperBuilder
private ValidationHelper(HelperBuilder helperBuilder) {
validatorHelpers = helperBuilder.innerValidatorHelpers;
}
public void setHelpers(ArrayList validatorHelpers) {
validatorHelpers = validatorHelpers;
}
public ArrayList getHelpers() {
return validatorHelpers;
}
}
EDIT/FIXED:
So for what it's worth, here's the revised builder. It needed another constructor that could properly initialize an instance of what it's supposed to build.
public class ValidationHelper {
private static ArrayList<HelperBuilder> validatorHelpers = new ArrayList();
public static class HelperBuilder {
private String txtFieldName;
private String txtFieldValue;
private List<Integer> valCodes = new ArrayList<Integer>();
private ArrayList<HelperBuilder> innerValidatorHelpers = new ArrayList<HelperBuilder>();
public HelperBuilder() {}
public HelperBuilder(String txtFieldName, String txtFieldValue, int[] validationCodes) {
this.txtFieldName = txtFieldName;
this.txtFieldValue = txtFieldValue;
for (int i = 0; i < validationCodes.length; i++) {
valCodes.add((Integer) validationCodes[i]);
}
}
public final HelperBuilder addHelper(String txtFieldName, String txtFieldValue, int[] validationCodes) {
innerValidatorHelpers.add( new HelperBuilder(txtFieldName, txtFieldValue, validationCodes) );
return this;
}
public final ValidationHelper build() {
return new ValidationHelper(this);
}
public String getTxtFieldName() {
return txtFieldName;
}
public String getTxtFieldValue() {
return txtFieldValue;
}
public List getValCodes() {
return valCodes;
}
}//end HelperBuilder
private ValidationHelper(HelperBuilder helperBuilder) {
validatorHelpers = helperBuilder.innerValidatorHelpers;
}
public ArrayList getHelpers() {
return validatorHelpers;
}
}
Each time you just overwrite the values in
private String txtFieldName;
private String txtFieldValue;
and the last one winns. So you create only 1 HelperInstance here
ValidationHelper v = new ValidationHelper.HelperBuilder()
and the fields name and value are overwritten each time you call addHelper(). But you need to create an instance for each "configuration". So addHelper should create a new Instance and add it into
private ArrayList<HelperBuilder> innerValidatorHelpers = ...;
If you want to build objects with different values you have to either
alter the builder between creating the objects so it will build something different.
instruct the builder to change the values automatically e.g. use a counter, or filename based on the date, or provide a list of values.