如何使用java在Array中获取用户输入?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2622725/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 10:00:00  来源:igfitidea点击:

how to take user input in Array using java?

javajava.util.scanner

提问by sadia

how to take user input in Array using Java? i.e we are not initializing it by ourself in our program but the user is going to give its value.. please guide!!

如何使用 Java 在 Array 中获取用户输入?即我们不会在我们的程序中自己初始化它,但用户会给出它的价值..请指导!!

采纳答案by polygenelubricants

Here's a simple code that reads strings from stdin, adds them into List<String>, and then uses toArrayto convert it to String[](if you reallyneed to work with arrays).

这是一个简单的代码,它从 中读取字符串stdin,将它们添加到 中List<String>,然后使用toArray将其转换为String[](如果您确实需要使用数组)。

import java.util.*;

public class UserInput {
    public static void main(String[] args) {
        List<String> list = new ArrayList<String>();
        Scanner stdin = new Scanner(System.in);

        do {
            System.out.println("Current list is " + list);
            System.out.println("Add more? (y/n)");
            if (stdin.next().startsWith("y")) {
                System.out.println("Enter : ");
                list.add(stdin.next());
            } else {
                break;
            }
        } while (true);
        stdin.close();
        System.out.println("List is " + list);
        String[] arr = list.toArray(new String[0]);
        System.out.println("Array is " + Arrays.toString(arr));
    }
}


See also:

也可以看看:

回答by Andrzej Doyle

It vastly depends on how you intend to take this input, i.e. how your program is intending to interact with the user.

这在很大程度上取决于您打算如何接受此输入,即您的程序打算如何与用户交互。

The simplest example is if you're bundling an executable - in this case the user can just provide the array elements on the command-line and the corresponding array will be accessible from your application's mainmethod.

最简单的例子是,如果您捆绑了一个可执行文件——在这种情况下,用户只需在命令行上提供数组元素,就可以从应用程序的main方法中访问相应的数组。

Alternatively, if you're writing some kind of webapp, you'd want to accept values in the doGet/doPostmethod of your application, either by manually parsing query parameters, or by serving the user with an HTML form that submits to your parsing page.

或者,如果您正在编写某种 web 应用程序,您可能希望通过手动解析查询参数或通过向用户提供提交到您的解析页面的 HTML 表单来接受应用程序的doGet/doPost方法中的值。

If it's a Swing application you would probably want to pop up a text box for the user to enter input. And in other contexts you may read the values from a database/file, where they have previously been deposited by the user.

如果它是一个 Swing 应用程序,您可能希望弹出一个文本框供用户输入。在其他上下文中,您可以从数据库/文件中读取值,这些值以前由用户存放在那里。

Basically, reading input as arrays is quite easy, once you have worked out a way to getinput. You need to think about the context in which your application will run, and how your users would likely expect to interact with this type of application, then decide on an I/O architecture that makes sense.

基本上,一旦你找到了一种获取input的方法,input作为数组读取就很容易。您需要考虑您的应用程序将在其中运行的上下文,以及您的用户可能希望如何与此类应用程序交互,然后决定一个有意义的 I/O 架构。

回答by flopex

import java.util.Scanner;

导入 java.util.Scanner;

class Example{

类示例{

//Checks to see if a string is consider an integer.

//检查一个字符串是否被认为是一个整数。

public static boolean isInteger(String s){

    if(s.isEmpty())return false;

    for (int i = 0; i <s.length();++i){

        char c = s.charAt(i);

        if(!Character.isDigit(c) && c !='-')

            return false;
    }

    return true;
}

//Get integer. Prints out a prompt and checks if the input is an integer, if not it will keep asking.

public static int getInteger(String prompt){
    Scanner input = new Scanner(System.in);
    String in = "";
    System.out.println(prompt);
    in = input.nextLine();
    while(!isInteger(in)){
        System.out.println(prompt);
        in = input.nextLine();
    }
    input.close();
    return Integer.parseInt(in);
}

public static void main(String[] args){
    int [] a = new int[6];
    for (int i = 0; i < a.length;++i){
        int tmp = getInteger("Enter integer for array_"+i+": ");//Force to read an int using the methods above.
        a[i] = tmp;
    }

}

}

}

回答by Santosh kumar shah

**How to accept array by user Input

**如何通过用户输入接受数组

Answer:-

回答:-

import java.io.*;

import java.lang.*;

class Reverse1  {

   public static void main(String args[]) throws IOException {

     int a[]=new int[25];

     int num=0,i=0;

     BufferedReader br=new BufferedReader(new InputStreamReader(System.in));

     System.out.println("Enter the Number of element");

     num=Integer.parseInt(br.readLine());

     System.out.println("Enter the array");

     for(i=1;i<=num;i++) {
        a[i]=Integer.parseInt(br.readLine());
     }

     for(i=num;i>=1;i--) {
        System.out.println(a[i]);    
     }

   }

}

回答by Busker Ott

package userinput;

import java.util.Scanner;

public class USERINPUT {

    public static void main(String[] args) {

        Scanner input = new Scanner(System.in);

        //allow user  input;
        System.out.println("How many numbers do you want to enter?");
        int num = input.nextInt();

        int array[] = new int[num];

        System.out.println("Enter the " + num + " numbers now.");

        for (int i = 0 ; i < array.length; i++ ) {
           array[i] = input.nextInt();
        }

        //you notice that now the elements have been stored in the array .. array[]

        System.out.println("These are the numbers you have entered.");
        printArray(array);

        input.close();

    }

    //this method prints the elements in an array......
    //if this case is true, then that's enough to prove to you that the user input has  //been stored in an array!!!!!!!
    public static void printArray(int arr[]){

        int n = arr.length;

        for (int i = 0; i < n; i++) {
            System.out.print(arr[i] + " ");
        }
    }

}

回答by nazmus saif

import java.util.Scanner;

class bigest {
    public static void main (String[] args) {
        Scanner input = new Scanner(System.in);

        System.out.println ("how many number you want to put in the pot?");
        int num = input.nextInt();
        int numbers[] = new int[num];

        for (int i = 0; i < num; i++) {
            System.out.println ("number" + i + ":");
            numbers[i] = input.nextInt();
        }

        for (int temp : numbers){
            System.out.print (temp + "\t");
        }

        input.close();
    }
}

回答by John

You can do the following:

您可以执行以下操作:

    import java.util.Scanner;

    public class Test {

            public static void main(String[] args) {

            int arr[];
            Scanner scan = new Scanner(System.in);
            // If you want to take 5 numbers for user and store it in an int array
            for(int i=0; i<5; i++) {
                System.out.print("Enter number " + (i+1) + ": ");
                arr[i] = scan.nextInt();    // Taking user input
            }

            // For printing those numbers
            for(int i=0; i<5; i++) 
                System.out.println("Number " + (i+1) + ": " + arr[i]);
        }
    }

回答by Anu Sathiya

int length;
    Scanner input = new Scanner(System.in);
    System.out.println("How many numbers you wanna enter?");
    length = input.nextInt();
    System.out.println("Enter " + length + " numbers, one by one...");
    int[] arr = new int[length];
    for (int i = 0; i < arr.length; i++) {
        System.out.println("Enter the number " + (i + 1) + ": ");
        //Below is the way to collect the element from the user
        arr[i] = input.nextInt();

        // auto generate the elements
        //arr[i] = (int)(Math.random()*100);
    }
    input.close();
    System.out.println(Arrays.toString(arr));