简体   繁体   English

如何在用户在 Java 中输入时从多行读取值并将它们保存到不同的数组

[英]How to read values from mutiple lines and save them to different array as user inputs them in Java

for instance user is inputting例如用户正在输入

1 3
3 4

i want to capture them in array1[] and array2[]我想在 array1[] 和 array2[] 中捕获它们

I tried below我在下面试过

for(int index = 0; index < count ; index++){
 while(!input.next().equals('\n')){
                int n = input.nextInt();
                if (n > 0 )
                    //save to two dimentional array 1st index is outer loop
            }
}

A Two Dimensional (2D) Array in Java is basically an Array of Arrays . Java 中的二维 (2D) 数组基本上是Array of Arrays This means that each array within that 2D Array can each be of different lengths if so desired.这意味着如果需要,该二维数组中的每个数组都可以具有不同的长度。 This can obviously be very handy for many different situations.对于许多不同的情况,这显然非常方便。

Your question appears to be in regards to only two specific lines consisting of only two numerical values in each entered line but the demo runnable code below demonstrates how you can allow the User to create a 2D int[][] array of any size.您的问题似乎仅与每个输入行中仅由两个数值组成的两个特定行有关,但下面的演示可运行代码演示了如何允许用户创建任意大小的 2D int[][] 数组。 That would of course be a 2D int[][] array consisting of any number of Rows with each row consisting of any number of Columns.那当然是一个由任意数量的行组成的二维 int[][] 数组,每行由任意数量的列组成。

As you know, arrays contain a fixed size and can not grow dynamically unless you create a new array to replace the old one.如您所知,数组包含固定大小并且不能动态增长,除非您创建一个新数组来替换旧数组。 The code below solves this problem by using two ArrayList objects which can grow dynamically, one of int[] ( ArrayList<int[]> ) and another of Integer ( ArrayList<Integer> ) then converting those ArrayList once all the data has been collected from the User.下面的代码通过使用两个可以动态增长的 ArrayList 对象来解决这个问题,一个是 int[] ( ArrayList<int[]> ),另一个是 Integer ( ArrayList<Integer> ),然后在收集到所有数据后转换这些 ArrayList来自用户。

Read the comments in code for additional information:阅读代码中的注释以获取更多信息:

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;


public class CreateATwoDimensionalINTArrayDemo {

    public static void main(String[] args) {
        // Scanner object to open stream for Keyboard Input
        Scanner userInput = new Scanner(System.in);
        
        // Declare the desired 2D Array to create...
        int[][] numbers2DArray;    
        
        /* An ArrayList of int[] arrays. Used so that our
           2D Array rows of int[] arrays can 'dynamically' 
           grow as needed.        */
        ArrayList<int[]> tmp2DArray = new ArrayList<>();
        
        /* Display what is required by the User to input
           via the keyboard to the Console Window. Pasting 
           each entry into each entry prompt can be done 
           as well if desired.        */
        System.out.println("You are required to enter lines of numbers where each\n"
                         + "number in a line is separated with at least one space.\n"
                         + "You can enter as many numbers as you like on each line.\n"
                         + "Enter nothing to stop entry and display the 2D Array\n"
                         + "you have created:\n");
        
        int lineCounter = 1;  // Just used for line entry prompt count.
        String line = "";     // Used to hold each each entry by the User.
        
        // Loop used to contiuously recieve numerical line entries from the User.
        while (line.isEmpty()) {
            // Get the numerical line from User...
            System.out.print("Enter line #" + lineCounter + ": --> ");
            // Increment the entry prompt count (by one).
            lineCounter++;  
            /* Get User input. Code flow stops here until the
               User hits the ENTER key within the Console Window. */
            line = userInput.nextLine().trim();
            /* If nothing is entered except the ENTER key 
               then exit this 'while' loop (quit).     */
            if (line.isEmpty()) { 
                System.out.println("< End Of Entery! >");
                System.out.println();
                break; 
            }
            
            /* Split the values entered in current entry 
               line into a String[] Array:  */
            String[] lineElements = line.split("\\s+");
            
            /* ENTRY VALIDATION for the above lineElements[] String Array!
               Only keep VALID value elements (elements that are proper Integer 
               of 'int' type numerical values) from the current User entered 
               data line. We don't want to deal elements that do not contain all
               numerical digits (typo type entry values).           */
            
            /* An ArrayList used to 'dynamically' create our inner int[] arrays.
               Ultimately, these will be the columnar values for the Rows of our
               2D Array.            */
            ArrayList<Integer> tmpList = new ArrayList<>();
            
            /* Iterate through the lineElemnts[] String array in order to 
               carry out validation on each array element and to convert
               each element into an integer (int) value.           */
            for (int i = 0; i < lineElements.length; i++) {
                /* Make sure there are no commas in the supplied 
                   numerical element (ex: 2,436). Some people have
                   a habbit of doing this.      */
                lineElements[i] = lineElements[i].replace(",", "");
                
                /* Is the supplied numerical element indeed a 
                   signed or unsigned INTEGER numerical value?  */
                if (lineElements[i].matches("-?\\d+")) {
                    /* Yes it is so parse the string numerical element into
                       an Long data type Integer so as to ensure it will meet
                       the required 'int' data type MAX_VALUE and MIN_VALUE 
                       threshold. */
                    long tmpLong = Long.parseLong(lineElements[i]);
                    if (tmpLong >= Integer.MIN_VALUE && tmpLong <= Integer.MAX_VALUE) {
                        /* Meets 'int' type numerical criteria so Cast the value 
                           in tmpLong to 'int' and add to the tmpList ArrayList.  */
                        tmpList.add((int)tmpLong); 
                    }
                }
            }
            
            //Convert the tmpList Integer ArrayList to an int[] Array
            int[] arr = new int[tmpList.size()];
            for (int k = 0; k < tmpList.size() ; k++) {
                arr[k] = tmpList.get(k);
            }
            
            /* Add the int[] array to the tmp2DArray ArrayList.   */
            tmp2DArray.add(arr);
            /* Clear the User line entry so as not to meet 
               the 'while' loop condition and the User can 
               enter another line.            */
            line = "";   
        }
        // ------------------ END OF WHILE LOOP ---------------------
        
        /* Convert the tmp2DArray<int[]> ArrayList to a 
           the numbers2DArray[][] 2D Array...        */
        numbers2DArray = new int[tmp2DArray.size()][];
        for (int i = 0; i < tmp2DArray.size(); i++) {
            numbers2DArray[i] = tmp2DArray.get(i);
        }
        
        // Display the 2D Array (if there is something in it to display)...
        System.out.println("===================================");
        System.out.println("Your 2D Array (numbers2DArray[][]):");
        System.out.println("-----------------------------------");
        if (numbers2DArray.length == 0) {
            System.out.println("- Nothing in 2D Array to display! -");
        }
        else {
            for (int i = 0; i < numbers2DArray.length; i++) {
                System.out.println("Array #" + (i+1) + ": --> " + Arrays.toString(numbers2DArray[i]));
            }
        }
        System.out.println("===================================");
    }
}

Play with it for a little while.玩一会儿。



Note how the numbers2DArray 2D Array is initialized注意numbers2DArray二维数组是如何初始化的

numbers2DArray = new int[tmp2DArray.size()][];

See how the second dimension doesn't receive a length value.查看第二个维度如何不接收长度值。 This leaves things open for internal arrays of any length.这为任何长度的内部数组留下了开放的空间。


About the Regular Expressions used within the code as arguments for both the String#split() and String#matches() methods:关于在代码中用作String#split()String#matches()方法参数的正则表达式

Expression: "\\\\s+"表达式: "\\\\s+"

Used as an argument for the String#split() method:用作String#split()方法的参数:

String[] lineElements = line.split("\\s+");

Split the string contained with the String variable line on every one (or more_ white-space ( \\\\s+ ) into a String Array named lineElements .将包含在每个字符串变量line上的字符串(或多个空格( \\\\s+ ))拆分为名为lineElements的字符串数组。


Expression: "-?\\\\\\\\d+"表达式: "-?\\\\\\\\d+"

Used as an argument for the String#matches() method:用作String#matches()方法的参数:

if (lineElements[i].matches("-?\\d+")) {

If the string element held in the lineElements String Array at index i optionally contains the negative or minus ( - ) character (the ? makes the - optional) followed by a string representation of an integer value of 1 or more digits ( \\\\d+ ) then carry out the code within that if code block.如果lineElements String Array 中索引i处的字符串元素可选地包含负号或减号 ( - ) 字符( ?使-可选)后跟 1 个或多个数字的整数值的字符串表示形式 ( \\\\d+ )然后执行该if代码块中的代码。

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

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