简体   繁体   English

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

[英]how to take user input in Array using java?

how to take user input in Array using Java?如何使用 Java 在数组中获取用户输入? ie we are not initializing it by ourself in our program but the user is going to give its value.. please guide!!即我们不是在我们的程序中自己初始化它,而是用户将给它的值.. 请指导!!

Here's a simple code that reads strings from stdin , adds them into List<String> , and then uses toArray to convert it to String[] (if you really need 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:也可以看看:

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] + " ");
        }
    }

}
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();
    }
}

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]);
        }
    }

It vastly depends on how you intend to take this input, ie 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 main method.最简单的例子是,如果你捆绑了一个可执行文件——在这种情况下,用户只需在命令行上提供数组元素,就可以从应用程序的main方法访问相应的数组。

Alternatively, if you're writing some kind of webapp, you'd want to accept values in the doGet / doPost method 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.如果它是一个 Swing 应用程序,您可能希望弹出一个文本框供用户输入。 And in other contexts you may read the values from a database/file, where they have previously been deposited by the user.在其他情况下,您可以从数据库/文件中读取值,这些值以前由用户存放在那里。

Basically, reading input as arrays is quite easy, once you have worked out a way to get input .基本上,一旦你找到了一种获取input 的方法,input作为数组读取就很容易 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.您需要考虑您的应用程序将在其中运行的上下文,以及您的用户可能希望如何与此类应用程序交互,然后决定一个有意义的 I/O 架构。

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;
    }

}

} }

**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]);    
     }

   }

}
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));

This is my solution if you want to input array in java and no.这是我的解决方案,如果你想在 java 中输入数组而不是。 of input is unknown to you and you don't want to use List<> you can do this.你不知道输入的数量,你不想使用 List<> 你可以这样做。

but be sure user input all those no.但请确保用户输入所有这些否。 in one line seperated by space在由空格分隔的一行中

 BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
 int[] arr = Arrays.stream(br.readLine().trim().split(" ")).mapToInt(Integer::parseInt).toArray();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM