import javax.swing.*;
public class mohamed {
static void tripleValue (int x,int y )
{
int c;
c=x;
x=y;
y=c;
}
public static void main(String[] args) {
String o;
int a;
o=JOptionPane.showInputDialog("insert a");
a=Integer.parseInt(o);
String l;
int b;
l=JOptionPane.showInputDialog("insert b");
b=Integer.parseInt(l);
tripleValue(a,b) ;
System.out.println("x="+a);
System.out.println("y="+b);
i write the program please tell me where is the error
I write aprogram to swap two numbers using function in java but the two numbers don't swap?
The "quick and dirty" way is to use single-element int arrays instead of ints.
static void tripleValue(int[] x, int[] y)
{
int c = x[0];
x[0] = y[0];
y[0] = c;
}
I really don't know why people keep asking this, as such a function seems of no value. Is this some school homework question?
Reply:Hai...
I think the problem is in the passing of the values to the function / procedure.
Since you are passing the variables the value, the values are swapping, but since you are not passing the variables by reference the memory location pointed by the variables x %26amp; y are not updating.
Retry by passing the address of the variables, (pass by reference)
In this way the address of the containing variables will be sent to the function and any change will immediately reflect in the original locations and in turn in the variable values.
Hope you have got the answer.
Happy Computing
Hare Krsna...
Reply:The variables are passed by value and objects are passed by reference to the function in java.
Since you are passing the variable only the value will be copied and any changes made to them will not be reflected, if you want the changes to be reflected the pass the objects.
so instead of using int give as integer in the function, that will make x,y as objects of integer type, and pass a,b (integer objects) to the function.
Reply:the parameters used are passed by reference but is first copied to be used within the function. I dont have the correct code for you but you can read a book on java and see how java handels references in functions i think you might need to use the Integer class in java yes thats it use the Integer class as the type for your parameters (Integer x, Integer y) and then change the values of the integer object within the method
wedding floral centerpieces
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment