3

A part of a small program I am coding:

String maxs = "";
int maxi = 0;

At this part I defined two variables as int and String.

public Class(String max){
   try {
           this.maxi = Integer.parseInt(max);
       }catch (Exception e){
           this.maxs = max;
       }
}

I think this way I will get to define one of both variables, if the String does not parse to int it will be saved as normal String.

Now I need to check what I need to return:

private TypeOfReturn getMax(){
    if(this.maxi == 0){
        // return maxs (return String)
    } else if (this.maxs.equals("")) {
        // return maxi (return int)
    } else return null;
}

The quastion is, how do I fill the missing parts of the method getMax()?

Is it even possiable in Java?

Subhi Samara
  • 77
  • 1
  • 2
  • 11

3 Answers3

1

Use Object instead of TypeOfReturn You can change the TypeoOfReturn to Object and then return the respective types.

1

Another way to find out fast if a string is a number or not, which is the main part of your program, is to use the lambda expressions in java 8 like this:

String max = "123";
boolean isNumber = max.chars().allMatch(Character::isDigit);
System.out.println(isNumber);

Which will give you the output

true
Alex Karlsson
  • 296
  • 1
  • 11
0

Make your TypeOfReturn as String object type and convert the maxi as String and return that String in your else if condition.

Note: you cannot return both the int and String in the Same method.

VNT
  • 934
  • 2
  • 8
  • 19