Reputation: 73
In this simple program i cant return 2 integer values , can you help me ? How can i do ?
public class Aritmetica
{
public static int div(int x , int y)
{
int q = 0 ;
int r = x ;
while ( r >= y )
{
r = r - y ;
q = q + 1 ;
}
return r && q; **// Here i want to return x and y**
}
public static void main(String[ ] args)
{
if ( ( x <=0 ) & ( y > 0 ) )
throw new IllegalArgumentException ( " X & Y must be >0 " ) ;
int res4= div(x,y);
System.out.println( " q and r : "+ res4) ; **// and here i want to display q and r**
}
}
Upvotes: 0
Views: 575
Reputation: 112
Assume q and r are less than p(can be any integer greater than q and r)
Now Do it like this
return result=q*p+r
Now, in main when you want to print the result
print q=result/p
r=result-p*q
Upvotes: 0
Reputation: 301
Instead of returning two integers at once, you can write separate methods for each operation. For example:
public static int div1(int x , int y) {
// i replaced r with x for readibility
while ( x >= y ) {
x = x - y ;
}
return x; // this is your variable r
}
public static int div2(int x, int y) {
int q = 0;
int r = x;
while ( r >= y ) {
r = r - y ; // r is required here because it is your update statement in while loop
q = q + 1 ;
}
return q;
}
In your main method, all you have to is call each method (div1 and div2 to get variables r and q, respectively). You can then print them with a statement like:
System.out.println( " q and r : "+ div2(x,y) + " and " + div1(x,y)) ;
I hope this is simple enough to understand. Good luck!
Upvotes: 0
Reputation: 421100
Create a result type: DivisionResult
, as follows:
class DivisionResult {
public final int quotient;
public final int remaineder;
public DivisionResult(int quotient, int remainder) {
this.quotient = quotient;
this.remainder = remainder;
}
}
and do
...
return new DivisionResult(q, r);
}
And to print the result:
DivisionResult res4= div(x,y);
System.out.println("q and r: " + res4.quotient + ", " + res4.remainder);
Upvotes: 5
Reputation: 3716
Use array of integers to return more than one integers.
Like :
public int[] method() {
int[] a = {1,2,3,4,5};
return a;
}
Upvotes: 0