-5

My code is:

int total = 10;
int[] myArray = new int [total];

System.out.println("Enter numbers.  To stop, enter 0.")

int numbers = input.nextInt();

while (numbers != 0) {
     for (int i = 0; i < total; i ++)
          myArray[i] = numbers;

     numbers = input.nextInt();
}

for (int i = 0; i < myArray.length; i++)
     System.out.print(myArray[i] + ", ") //This line only prints the last number I enter 10 times.

I want to be able to print the whole array with the numbers I entered. For example:

I enter: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 0

But the result I get is: 10, 10, 10, 10, 10, 10, 10, 10, 10, 10

EDIT: I don't get why my question has been marked a duplicate? I tried searching everywhere on this site for a similar question and haven't found one so that's why I asked. Isn't this the purpose of this site?

EDIT 2: Fine. I see how it is. I'll take my questions to some other more helpful sites. Thank you for your "service" Stack Exchange.

5120bee
  • 689
  • 1
  • 14
  • 36

2 Answers2

1

Your for loop is resetting all of the items in the array each time. I doubt that you meant to do that.

jsight
  • 27,819
  • 25
  • 107
  • 140
  • I see. But if I take out the input line in the while loop, how will I be able to stop the looping when the user enters a `0`? – 5120bee Sep 25 '16 at 19:02
  • numbers != 0 on your while loop is correct, you just have to remove the for loop inside the while loop and add another condition that will check if user has already filled all the arrays. something like while (numbers != 0 || counter < total) Then ofcourse you have to assign the input into your array and update the counter – Chris Laconsay Sep 25 '16 at 19:10
0

You can do this:

  1. Declare i outside while loop and initialize it with 0.
  2. Change the while loop's condition to numbers != 0 && i < total.
  3. Remove the for loop inside your while loop.
  4. Instead just write myArray[i] = numbers; and i++; to replace the for loop.

Here's the code:

int numbers = input.nextInt();
int i = 0;
while (numbers != 0 && i < total) {
    myArray[i] = numbers;
    i++;
    numbers = input.nextInt();
}

Here's your code working fine.

Ahmad Khan
  • 2,655
  • 19
  • 25