Can't figure out what's wrong
Question.
The user should input non negative integers, These values must be filled in an array of 10 elements. If the user enters -1, or the array becomes full whatever comes first, the program should terminate. The output should be the value of integers entered by the user in the reverse order.
My Problem:
When I enter -1, the -1 also gets displayed in the array.It should display non negative integers, the -1 is a condition to break out of the loop.
Also if I enter -1, the elements in the array that are not filled display 0. I don't want 0 to be displayed if the value of elements are null.
Code java:
import java.util.Scanner;
public class whatswrong {
public static void main(String[] args) {
int array[];
int i=0, userInput;
array = new int[10];
Scanner scan = new Scanner (System.in);
while (i <= 10){
System.out.println("Please enter a positive integer or -1 to quit");
userInput = scan.nextInt();
array[i] = userInput;
i++;
if (i == 10)
break;
if (userInput < -1)
i--;
if (userInput == -1)
break;
}
int[] reverse = new int[10];
int revIndex = 0;
for (int j = array.length -1 ; j >= 0; j--){
reverse[revIndex] = array[j];
revIndex++;
}
System.out.println("reverse: ");
for (int k = 0; k < array.length; k++)
System.out.println(reverse[k]);
}
}
Re: Can't figure out what's wrong
You're trying to do a few things at once here. Break your problem down into smaller steps. Specifically, separate the code that's getting user input from the code that's reversing the array. Which one isn't working? Then step through it with a debugger, or at least at some print statements, to figure out exactly when the code does something different from what you expect.