简体   繁体   English

Java - 将用户输入转换为二维整数数组

[英]Java - Convert user input to 2d integer array

How do I convert user input of (first input is size):如何转换用户输入(第一个输入是大小):

4
1 2
3
3
-1

to an equivalent of :相当于:

int graph[][] = {{1,2},{3},{3},{}};

My attempt is:我的尝试是:

        Scanner sc = new Scanner(System.in);

        int n = sc.nextInt();

        int graph2[][] = {{1,2},{3},{3},{}};
        int graph[][] = new int[n][n];

        for (int i = 0; i < n; i++) {
                int counter = 0;
                char[] arr = sc.nextLine().toCharArray();
                for (char c : arr){
                    graph[i][counter++] = (int)c-48;
                }

        }
        System.out.println(Arrays.deepToString(graph2));
        System.out.println(Arrays.deepToString(graph));

However, I have to input without space:但是,我必须在没有空格的情况下输入:

4
12
3
3

The output is :输出是:

Need it in : [[1, 2], [3], [3], []]
Crrent Output : [[0, 0, 0, 0], [1, 2, 0, 0], [3, 0, 0, 0], [3, 0, 0, 0]]

Some simple code:一些简单的代码:

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

public class Array2D {
public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    int size = in.nextInt();
    //consume the extra line
    in.nextLine();  
    int[][] array = new int[size][];
    for(int i = 0 ;i <size; i++) {
        String line = in.nextLine();
        array[i] = toIntArray(line.split(" "));
    }
}

public static int[] toIntArray(String[] arr){
    int intArray[] = new int[arr.length];
    for(int i=0;i<arr.length;i++) {
        intArray[i] = Integer.parseInt(arr[i]);
    }
    return intArray;
}

} }

I have the below code working for me, at least for the test case you mentioned.我有以下代码为我工作,至少对于您提到的测试用例。 I am not sure if you are restricted to use Arrays only我不确定您是否仅限于使用数组

public static void main(String[] args) throws Exception {
    //The part to take input from user
    BufferedReader  br = new BufferedReader (new InputStreamReader(System.in));
    
    //Take the first input and parse it to Integer
    int T = Integer.parseInt(br.readLine());
    
    //Create a new arraylist which can fit as per input
    ArrayList<ArrayList<Integer>> graph = new ArrayList<>();
    
    //Will take inputs from user T times
    while(T-- >0) {
        //Handle the case for space separated inputs 
        String[] inp = br.readLine().split(" ");
        
        ArrayList<Integer> inner = new ArrayList<>();
        
        //If there are any elements in current line of input , convert it to Integer by parsing and add to inner array
        for(String s : inp) {
            if(Integer.parseInt(s) >= 0) {
            inner.add(Integer.parseInt(s));
            }
        }
        
        graph.add(inner);
    }
    
    System.out.println(" Graph is " + graph);
    // Graph is [[1, 2], [3], [3], []]
        
}

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

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