How to exchange / exchange the value of two variables

3

I'm having trouble writing this exercise in the Java Language, using the Eclipse IDE:

  

Read two values for the variables A and B, change the values so that the variable A has the value of the variable B and that the variable B has the value of the variable A. Display the values exchanged .

I know I need to declare Variable A, Variable B, and an Auxiliary Variable!

In this case I can only make Variable A get the value of Variable B! But Variable B presents the value itself and does not present the Value of A which is what I need!

MY CODE:

import java.io.IOException;
import java.util.Scanner;

public class Variavel {

    public static void main(String[] args) throws IOException {

     int VarA;
     int VarB;
     int Aux;

     System.out.println("Digite a Primeira Variavel");

     Scanner Lera = new Scanner(System.in);
     VarA= Lera.nextInt();

     System.out.println("Digite a Primeira Variavel");
     VarB= Lera.nextInt();



     VarA=VarB;

     Aux=VarA;

     VarB=Aux;

     System.out.println("O valor de A é: " +VarB);
     System.out.println("O valor de B é: " +Aux);
     Lera.close();



    }

}
  

NOTE: I'm at the beginning of JAVA Classes, so for now I only use the basic commands like INT, Scanner, Read? I have not yet learned FOR, WHILE, IF, ELSE

IMAGE OF RESULT

    
asked by anonymous 09.03.2018 / 15:19

2 answers

4

You have two problems.

The way to trade is wrong, as is the way you use variables in println as well.

Change to:

//Guarada o valor de A
Aux=VarA;
//A variável VarA, como já foi guardado o valor de A, pode agora receber o valor de B
VarA=VarB;
//O valor de A, anteriormente guardado na variável Aux, é atribuído à variável VarB
VarB=Aux;

//Como as variáveis têm agora os valores trocados deve usá-las no println na sequência correcta
System.out.println("O valor de A é: " +VarA);
System.out.println("O valor de B é: " +VarB);
    
09.03.2018 / 15:29
6

Your error was to change the value of the variable VarA before storing the value of it in the variable Aux :

 Aux=VarA;
 VarA=VarB;
 VarB=Aux;

This will work correctly. Also change the view:

 System.out.println("O valor de A é: " +VarA);
 System.out.println("O valor de B é: " +VarB);

This will display the variables already with the changed values, as can be seen in the ideone: link

Note that in Java, variable names must start with a lowercase letter, following the Camel Case for names compounds.

    
09.03.2018 / 15:21