Need To Take Input To Array Until User Enters 0 JAVA

女生的网名这么多〃 提交于 2019-12-30 05:37:05

问题


I need help understanding how to write a for loop that takes in a certain amount of integers (must be 1 through 10) and it stops taking in numbers once 0 is entered (0 will be the last number). My code so far is:

   import java.util.Scanner;
   public class countNum {

      public static void main(String[] args) {

        int[] array;

        Scanner input = new Scanner(System.in);
        System.out.println ("Enter in numbers (1-10) enter 0 when finished:");

        int x = input.nextInt();

        while (x != 0) {
          if (x > 2 && x < 10) {
          //Don't know what to put here to make array[] take in the values
          }
          else
          //Can I just put break? How do I get it to go back to the top of the while loop?
        }
      }   

     }

}

I don't understand how to simultaneously initialize an array with a set length while having the Scanner read a certain amount of digits of that unknown length, until 0 is entered, and then the loop stops taking in input for the array.

Thanks for any help!


回答1:


Ok here's the bit more detail: -

  • You need to use an ArrayList if you want a dynamically increasing array. You do it like this: -

    List<Integer> numbers = new ArrayList<Integer>();
    
  • Now, in your above code, you can put your number reading statement (nextInt) inside the while loop, since you want to read it regularly. And put a condition in while loop to check whether the entered number is an int or not: -

    int num = 0;
    while (scanner.hasNextInt()) {
        num = scanner.nextInt();
    }
    
  • Further, you can move on your own. Just check whether the number is 0 or not. If it is not 0, then add it to ArrayList: -

    numbers.add(num);
    
  • If its 0, break out of your while loop.

  • And you don't need that x != 0 condition in your while loop, as you are already checking it inside the loop.




回答2:


In your case, the user seems to be able to input any number of digits. For this scenario, having an array is not ideal simply because the size of the array needs to be known prior to the array initialization. You have some options though:

  1. Use an ArrayList. This a dynamic data structure which expands dynamically.
  2. Ask the user the amount of numbers he/she is going to be entering and use that to initialize the array.
  3. Create an array basing yourself on some assumption on the size.

In both cases 2 and 3, you would also need to include some logic that will make the program stop when: (1) The user enters 0 (2) OR when the amount of numbers provided by the user exceeds the size of the array.

I would recommend sticking to the first solution though since it is easier to implement.




回答3:


I strongly recommend you go get some hands on with Java Collections.

you can fix your program as

import java.util.ArrayList;
import java.util.InputMismatchException;
import java.util.List;
import java.util.Scanner;

  public class arrayQuestion {

    public static void main(String[] args) {

        List<Integer> userInputArray = new ArrayList<Integer>();

        Scanner input = new Scanner(System.in);
        System.out.println("Enter 10 Numbers ");
        int count = 0;
        int x;
        try {
            do {
                x = input.nextInt();
                if (x != 0) {
                    System.out.println("Given Number is " + x);
                    userInputArray.add(x);
                } else {
                    System.out
                            .println("Program will stop Getting input from USER");
                    break;
                }
                count++;
            } while (x != 0 && count < 10);

            System.out.println("Numbers from USER : " + userInputArray);
        } catch (InputMismatchException iex) {
            System.out.println("Sorry You have entered a invalid input");
        } catch (Exception e) {
            System.out.println("Something went wrong :-( ");
        }

        // Perform Anything you want to do from this Array List

    }
}

I hope this will solve your doubt.. beyond this u need to handle Exceptions if user enters any character or invalid inputs as above



来源:https://stackoverflow.com/questions/13023716/need-to-take-input-to-array-until-user-enters-0-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!