I'm having trouble doing my code since I'm learning from scratch I don't have any idea how I'm going to print out a reversed input from my array. This is what I have so far:
import java.util.Scanner;
public class ReverseList {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int[] array = new int[10];
int num = 0;
int count = 0;
int total = 1;
loop:
for (count = 0; count <= 10; count ) {
System.out.print("Enter a number (999 to quit): ");
num = scan.nextInt();
if (num == 999) {
break loop;
}
if (count == 9) {
break loop;
}
array[count] = num;
total = count 1;
}
System.out.print("\n The list reversed is:" );
//List Reversed
}
}
And the application output should look similar to:
Enter a number (999 to quit): 19 <enter>
Enter a number (999 to quit): 44 <enter>
Enter a number (999 to quit): 25 <enter>
Enter a number (999 to quit): 16 <enter>
Enter a number (999 to quit): 999 <enter>
The list reversed is: 16 25 44 19
CodePudding user response:
Your current code has a few bugs. First, total
should be incremented by one (not count
). You should not embed a test on count
in the loop. You should not rely on so many different magic numbers. Finally, to print the array contents reversed start with the total number of elements and count backwards. Like,
Scanner scan = new Scanner(System.in);
int[] array = new int[10];
int total = 0;
for (int count = 0; count < array.length; count ) {
System.out.print("Enter a number (999 to quit): ");
int num = scan.nextInt();
if (num == 999) {
break;
}
array[count] = num;
total ;
}
System.out.println("The list reversed is:");
for (int count = total - 1; count >= 0; count--) {
System.out.println(array[count]);
}
CodePudding user response:
Do some loop but reversed with i--
.
Little explanation:
int i
value will be 9, i >= 0
doing this loop to array index 0, i--
will decrease the value each time iteration executed.
for (int i = array.length-1; i >= 0; i--){
System.out.print(array[i] " ");
}