如何返回两个整数

时间:2014-11-02 18:43:55

标签: java integer return

在这个简单的程序中我不能返回2个整数值,你能帮帮我吗? 我能怎么做 ?

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** 

}

}

4 个答案:

答案 0 :(得分:5)

创建结果类型:DivisionResult,如下所示:

class DivisionResult {
    public final int quotient;
    public final int remaineder;
    public DivisionResult(int quotient, int remainder) {
        this.quotient = quotient;
        this.remainder = remainder;
    }
}

并做

    ...
    return new DivisionResult(q, r);
}

打印结果:

  DivisionResult res4= div(x,y);

  System.out.println("q and r: " + res4.quotient + ", " + res4.remainder);

答案 1 :(得分:0)

使用整数数组返回多个整数。

喜欢:

public int[] method() {  
    int[] a = {1,2,3,4,5};  
    return a;   
}  

答案 2 :(得分:0)

假设q和r小于p(可以是大于q和r的任何整数)

现在就这样做

return result=q*p+r

现在,在主要打印结果时

print q=result/p
r=result-p*q

答案 3 :(得分:0)

您可以为每个操作编写单独的方法,而不是一次返回两个整数。例如:

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;
}

在你的main方法中,你只需要调用每个方法(div1和div2分别得到变量r和q)。然后,您可以使用如下语句打印它们:

System.out.println( " q and r : "+ div2(x,y) + " and " + div1(x,y)) ;

我希望这很容易理解。祝你好运!