-1

I have a method which calculates the square root of only negative numbers

(which is sqrt(x)=sqrt(-x) +"*i" , where x is a double and "*i" is a string)

the problem I have is that this method returns a double and a string which are two different variable types, so the question is how do I make this method return both?:

public static **(what goes here?)** myFunction(double x){

    return(sqrt(x)+"*i");

}

this code is wrong but I do not know how to fix it, any tips?

jhamon
  • 3,603
  • 4
  • 26
  • 37
  • 3
    You can write a class that contains a string and an int, and return an instance of that. Not clear from your question why you need to return a string and an int from this particular method. If you want to return `sqrt(x)+"*i"`, that's just a string. – khelwood Oct 04 '18 at 09:16
  • This may be helpful: https://stackoverflow.com/questions/2997053/does-java-have-a-class-for-complex-numbers – ernest_k Oct 04 '18 at 09:16
  • khelwood I think I might, ernest_k, it would be helpful if I knew what it meant, i'm still knew to this. luk2303 not a duplicate, I don't know what an object is (yet, my teacher said we will learn about it in about 8 months). – sandro Hakim Arrangements Oct 04 '18 at 09:25
  • You not knowing what an object is does not matter to us. We will not explain the basic concepts of OOP to you. – luk2302 Oct 04 '18 at 09:30
  • You don't need to return both: you just need to return a type that represents an imaginary number. The "*i" is purely presentation. – Andy Turner Oct 04 '18 at 09:43
  • 2
    "we will learn about it in about 8 months" I would suggest there isn't 8 months of stuff to learn in Java without objects. They're fundamental. – Andy Turner Oct 04 '18 at 09:45
  • @andyTurner haha I always work ahead (ex. why im asking this, my classroom is doing random numbers) – sandro Hakim Arrangements Oct 04 '18 at 10:06
  • @andyTurner and what do you mean with the representation of an imaginary number? – sandro Hakim Arrangements Oct 04 '18 at 10:11
  • @luk2302 isn't the purpose of asking questions to understand things you do not have knowledge of? – sandro Hakim Arrangements Oct 04 '18 at 10:13

1 Answers1

2

In Java you can't return multiple values from methods.

What you could do is to define a custom type which wraps your string and double values. Eg:

public class MyResult {
    private double res1;
    private String res2;

    public MyResult(double res1, String res2) {
        this.res1 = res1;
        this.res2 = res2;
    }
}

And use this in your method:

public static MyResult myFunction(double x){
    return new MyResult(sqrt(x),"*i");
}
Amila
  • 5,195
  • 1
  • 27
  • 46