1. 程式人生 > >Java——解析二維陣列

Java——解析二維陣列

Description

讀入一個字串,該字串表示一個整型二維陣列d,陣列中的元素通過解析字串引數獲得。例如,字串引數:“1,2;3,4,5;6,7,8”,對應的陣列為:
d[0,0] = 1 d[0,1] = 2  
d[1,0] = 3 d[1,1] = 4 d[1,2] = 5
d[2,0] = 6 d[2,1] = 7 d[2,2] = 8
列印這個陣列各元素的內容

Input

字串

Output

二維陣列各元素

Sample Input

1,2;3,4,5;6,7,8

Sample Output

d[0,0] = 1 d[0,1] = 2
d[1,0] = 3 d[1,1] = 4 d[1,2] = 5
d[2,0] = 6 d[2,1] = 7 d[2,2] = 8
import java.util.*;

public class Main {

    public static void main(String[] args) {

    Scanner scan = new Scanner(System.in);

    String str = scan.nextLine();

    System.out.print("d[0,0] = " + str.charAt(0));

    int col = 0;//列

    int row = 0;//行

    for(int i = 1;i<str.length();i++)

    {

        if(str.charAt(i) == ',')

        {

            System.out.print(" ");

            col ++;

            System.out.print("d[" + row + "," + col + "] = ");

        }

        if(str.charAt(i) == ';')

        {

            System.out.println();

            row ++;

            col = 0;

            System.out.print("d[" + row + "," + col + "] = ");

        }

        else if(str.charAt(i) >= '0' && str.charAt(i) <= '9')

        {

            System.out.print(str.charAt(i));

        }

    }

}

    

}


/*