Java/swap 2 numbers
Expert: Brian Ngure - 9/3/2009
QuestionQUESTION: Hi,
I wanna simple java code to swap 2 numbers without using 3rd variable and these 2 numbers should be taken from the user.i.e., user gv an input of 2 numbers, those 2 numbers should be swaped.
ANSWER: Hi,
You could just reverse the order of the output in the code.
i.e. Instead of writing print(num1 + " " + num2); write print(num2 + " " + num1);
Brian
---------- FOLLOW-UP ----------
QUESTION: public class SwapTwoNumbers
{
public static void main(String[] args)
{
int a=1;
int b=2;
System.out.println("Before swap: a="+a+"b="+b);
a=a+b;
b=a-b;
a=a-b;
System.out.println(" After swap: a="+a+"b="+b);
}
}
Here is the code for swaping 2 numbers without using third variable. But here 'a' and 'b' value are already set in code. Here 'a' and 'b' value should be taken by user.
can you please tell me. how to do this ?
AnswerHi,
Here is a simple example of how to get keyboard input:
import java.io.*;
public class TestReadLine {
public static void main (String args[]) {
String aLine = "";
BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
try {
aLine = input.readLine();
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(aLine);
}
}
Brian