Java/swap 2 numbers

Advertisement


Question
QUESTION: 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 ?

Answer
Hi,

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

Java

All Answers


Answers by Expert:


Ask Experts

Volunteer


Brian Ngure

Expertise

Strong in Java. Will be able to answer both in areas of designing and coding. Some knowledge in servlets

Experience

5 years of Java experience, Sun Certified Java Associate and Sun Certified Java Programmer, JDK 1.4

©2012 About.com, a part of The New York Times Company. All rights reserved.