Java Lab: Swapping Variables

preview_player
Показать описание
----------------------------------------------------------------------------------------
Social media:
----------------------------------------------------------------------------------------

Code in comments
Рекомендации по теме
Комментарии
Автор

Thank you for the tutorial. Quick question. Is the scnr.close(); very important? I ran one without it and it still works. Would you explain why it seems to be a good practice? Thank you so much.

edwardwung
Автор

import java.util.Scanner;

public class SwappingVariables {
public static void swapValues(int[] values) { // Then this part sends the values the user inputed below for it to be swapped.
int temporaryHolder;
temporaryHolder = values[0]; // A temporary holder is needed to hold the first value
values[0] = values[1]; // So the first value can equal the second
values[1] = temporaryHolder; // and the second can equal the first.

}

public static void main(String[] args) { // The compiler will begin reading here since this is the main method
Scanner scnr = new Scanner(System.in);
int[] values = new int[2]; // This is so that a maximum of 2 index are available (they are saved into values).
values[0] = scnr.nextInt(); // The user will enter the first integer which is saved in the first index
values[1] = scnr.nextInt(); // The user will enter the first integer which is saved in the second index

swapValues(values); // This function calls the above part of the program.

System.out.println(values[0] + " " + values[1]); // The compiler hits this part with the values swapped.
scnr.close();
}
}

collegehelper
visit shbcf.ru