简体   繁体   中英

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[]

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 . 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. That would of course be a 2D int[][] array consisting of any number of Rows with each row consisting of any number of Columns.

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.

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 = 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:

Expression: "\\\\s+"

Used as an argument for the String#split() method:

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 .


Expression: "-?\\\\\\\\d+"

Used as an argument for the String#matches() method:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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