Created
March 19, 2019 02:28
-
-
Save davidauza-engineer/73828ad1dd567073d934227c27850cd5 to your computer and use it in GitHub Desktop.
Console program in Java to reverse an array created by the user.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.Arrays; | |
import java.util.Scanner; | |
public class ArrayReverse { | |
static int arraySize; | |
public static void main(String[] args) { | |
int[] array; | |
int[] reversedArray; | |
boolean validArraySize = false; | |
boolean validInteger = false; | |
String errorSize = "\nError. Not a valid array size. Please insert an integer number greater than 0."; | |
Scanner sc = new Scanner(System.in); | |
System.out.println("\nWelcome to the program to reverse an integer array."); | |
// The user is prompted to determine the size of the array | |
while (!validArraySize) { | |
System.out.println("\nPlease insert the size of the array"); | |
if (sc.hasNextInt()) { | |
arraySize = sc.nextInt(); | |
if (arraySize > 0) { | |
validArraySize = true; | |
} else { | |
// The user entered an integer number less or equal to 0. | |
System.out.println(errorSize); | |
} | |
} else { | |
// The user did not enter an integer number. | |
System.out.println(errorSize); | |
} | |
} | |
// The array is created with the specified size | |
array = new int[arraySize]; | |
// The user is prompted to enter the value for each position of the array | |
for (int i = 0; i < array.length; i++) { | |
while (!validInteger) { | |
System.out.println("\nPlease insert the value for position " + i + ":"); | |
if (sc.hasNextInt()) { | |
array[i] = sc.nextInt(); | |
validInteger = true; | |
} else { | |
System.out.println("\nError. Please insert a valid integer number."); | |
} | |
} | |
validInteger = false; | |
} | |
sc.close(); | |
System.out.println("\nThe array you entered is: " + Arrays.toString(array)); | |
reversedArray = reverseArray(array); | |
System.out.println("\nThe reversed array is: " + Arrays.toString(reversedArray)); | |
} | |
/** | |
* This method reverses the array specified | |
* | |
* @param pArray The array to reverse | |
* @return The reversed array | |
*/ | |
public static int[] reverseArray(int[] pArray) { | |
int[] arrayToReturn = new int[arraySize]; | |
int indexToReverse = arraySize - 1; | |
for (int i = 0; i < arrayToReturn.length; i++) { | |
arrayToReturn[i] = pArray[indexToReverse]; | |
indexToReverse--; | |
} | |
return arrayToReturn; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment