4

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?

5
  • 3
    TypeOfReturn can be Object. Commented Mar 31, 2017 at 14:15
  • this.maxi = Integer.parseInt(max); where the max come from ? Commented Mar 31, 2017 at 14:16
  • check this stackoverflow.com/questions/2127318/… Commented Mar 31, 2017 at 14:18
  • Is this for a school assignment? Or is there another purpose for this in your program? There are probably many other ways that are better if this isnt a specific assignment. Commented Mar 31, 2017 at 14:24
  • @mustafacil Object did good job. Commented Mar 31, 2017 at 14:25

3 Answers 3

2

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

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

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.

1 Comment

I changed the TypeOfReturn to Object. it did work. thanks anyway

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.