【问题标题】:How to read values from mutiple lines and save them to different array as user inputs them in Java当用户在Java中输入它们时,如何从多行读取值并将它们保存到不同的数组中
【发布时间】:2021-10-18 11:31:29
【问题描述】:

例如 用户正在输入

1 3
3 4

我想在 array1[] 和 array2[] 中捕获它们

我在下面尝试过

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

【问题讨论】:

  • 1 3 在第一行,3 4 在下一行
  • 您到底遇到了什么问题?您预期的最终结果是什么?
  • 看来inputScanner,这意味着您的代码将永远无法工作。 Scanner 使用空白序列作为分隔符将输入分解为标记。 \n 是一个空白字符,因此input.next() 永远不会返回。另一个问题是 input.next() 返回下一个令牌 - 如果您不存储对该令牌的引用(例如,仅在其上调用 .equals()),则令牌将丢失。

标签: java arrays java.util.scanner


【解决方案1】:

Java 中的二维 (2D) 数组 基本上是 ArraysArray。这意味着如果需要,该 2D 数组中的每个数组都可以具有不同的长度。对于许多不同的情况,这显然非常方便。

您的问题似乎是关于在每个输入的行中仅包含两个数值的两个特定行,但下面的演示可运行代码演示了如何允许用户创建任何二维 int[][] 数组尺寸。这当然是一个 2D int[][] 数组,由任意数量的行组成,每行由任意数量的列组成。

如您所知,数组包含固定大小并且不能动态增长,除非您创建一个新数组来替换旧数组。下面的代码通过使用两个可以动态增长的 ArrayList 对象来解决这个问题,一个是 int[] (ArrayList&lt;int[]&gt;),另一个是 Integer (ArrayList&lt;Integer&gt;),然后在从用户那里收集到所有数据后转换这些 ArrayList。

阅读代码中的 cmets 以获取更多信息:

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

玩一会儿。



注意numbers2DArray 2D 数组是如何初始化的

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

查看第二个维度如何不接收长度值。这为任何长度的内部数组打开了大门。


关于在代码中用作String#split()String#matches() 方法的参数的Regular Expressions

表达式:"\\s+"

用作String#split() 方法的参数:

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

将每个字符串变量line 包含的字符串(或更多_空格(\\s+)拆分为一个名为lineElements 的字符串数组。


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

用作String#matches() 方法的参数:

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

如果 lineElements 字符串数组中索引 i 处的字符串元素可选地包含负号或减号 (-) 字符(? 使 - 可选)后跟字符串表示一个 1 位或更多位的整数值 (\\d+) 然后执行该 if 代码块内的代码。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-20
    • 2022-07-27
    • 2021-06-09
    • 2015-02-20
    • 1970-01-01
    相关资源
    最近更新 更多