2013-12-05 4 views
-1

Im не совсем понимая 2D массивы ...Java преобразования 1D массив в 2D

У меня есть этот 1D массив, и я хочу, чтобы преобразовать его в 2D, так что число в одном измерении, а описание в другой.

Это мой текущий массив:

String[] errorcodes = { 
     "1|Failed to set a UBC parameter", 
     "2|Failed to set a fair scheduler parameter", 
     "3|Generic system error", 
     "5|The running kernel is not an OpenVZ kernel (or some OpenVZ modules are not loaded)", 
     "6|Not enough system resources", 
     "7|ENV_CREATE ioctl failed", 
     "8|Command executed by vzctl exec returned non-zero exit code", 
     "9|Container is locked by another vzctl invocation", 
     "10|Global OpenVZ configuration file vz.conf(5) not found", 
     "11|A vzctl helper script file not found", 
     "12|Permission denied", 
     "13|Capability setting failed", 
     "14|Container configuration file ctid.conf(5) not found", 
     "15|Timeout on vzctl exec", 
     "16|Error during vzctl suspend", 
     "17|Error during vzctl resume", 
     "18|Error from setluid() syscall", 
     "20|Invalid command line parameter", 
     "21|Invalid value for command line parameter", 
     "22|Container root directory (VE_ROOT) not set", 
     "23|Container private directory (VE_PRIVATE) not set", 
     "24|Container template directory (TEMPLATE) not set", 
     "28|Not all required UBC parameters are set, unable to start container", 
     "29|OS template is not specified, unable to create container", 
     "31|Container not running", 
     "32|Container already running", 
     "33|Unable to stop container", 
     "34|Unable to add IP address to container", 
     "40|Container not mounted", 
     "41|Container already mounted", 
     "43|Container private area not found", 
     "44|Container private area already exists", 
     "46|Not enough disk space", 
     "47|Bad/broken container (/sbin/init or /bin/sh not found)", 
     "48|Unable to create a new container private area", 
     "49|Unable to create a new container root area", 
     "50|Unable to mount container", 
     "51|Unable to unmount container", 
     "52|Unable to delete a container", 
     "53|Container private area not exist", 
     "60|vzquota on failed", 
     "61|vzquota init failed", 
     "62|vzquota setlimit failed", 
     "63|Parameter DISKSPACE not set", 
     "64|Parameter DISKINODES not set", 
     "65|Error setting in-container disk quotas", 
     "66|vzquota off failed", 
     "67|ugid quota not initialized", 
     "71|Incorrect IP address format", 
     "74|Error changing password", 
     "78|IP address already in use", 
     "79|Container action script returned an error", 
     "82|Config file copying error", 
     "86|Error setting devices (--devices or --devnodes)", 
     "89|IP address not available", 
     "91|OS template not found", 
     "99|Ploop is not supported by either the running kernel or vzctl.", 
     "100|Unable to find container IP address", 
     "104|VE_NETDEV ioctl error", "105|Container start disabled", 
     "106|Unable to set iptables on a running container", 
     "107|Distribution-specific configuration file not found", 
     "109|Unable to apply a config", 
     "129|Unable to set meminfo parameter", 
     "130|Error setting veth interface", 
     "131|Error setting container name", 
     "133|Waiting for container start failed", 
     "139|Error saving container configuration file", 
     "148|Error setting container IO parameters (ioprio)", 
     "150|Ploop image file not found", 
     "151|Error creating ploop image", 
     "152|Error mounting ploop image", 
     "153|Error unmounting ploop image", 
     "154|Error resizing ploop image", 
     "155|Error converting container to ploop layout", 
     "156|Error creating ploop snapshot", 
     "157|Error merging ploop snapshot", 
     "158|Error deleting ploop snapshot", 
     "159|Error switching ploop snapshot", 
     "166|Error compacting ploop image", 
     "167|Error listing ploop snapsots", }; 

Я хотел бы быть в состоянии сделать это в одной строке, так же, как это.

+0

'String [] [] array = {{" 123 "," a "}, {" b "," 343 "}};' – nachokk

+1

Вы действительно не хотите видеть карту? Вы хотите, чтобы это как 'String [] []'? –

+0

Не волнуйтесь, вы можете написать даже 1000 слов кода в одной строке. – Baby

ответ

0

Вы можете сделать это на основе вашей существующей errorcodes

String[][] errorcodesArray = new String[errorcodes.length][2]; 
for (int i = 0; i < errorcodes.length; i++) { 
    StringTokenizer st = new StringTokenizer(
     errorcodes[i], "|"); 
    if (st.hasMoreTokens()) 
    errorcodesArray[i][0] = st.nextToken(); 
    if (st.hasMoreTokens()) 
    errorcodesArray[i][1] = st.nextToken(); 
} 
for (int i = 0; i < errorcodesArray.length; i++) { 
    System.out.println(Arrays 
     .toString(errorcodesArray[i])); 
} 

или код сделать это автономный

String[][] errorcodesArray = { 
    { "1", "Failed to set a UBC parameter"}, 
    { "2", "Failed to set a fair scheduler parameter"}, 
    { "3", "Generic system error"}, 
    { "5", "The running kernel is not an OpenVZ kernel (or some OpenVZ modules are not loaded)"}, 
    { "6", "Not enough system resources"}, 
    { "7", "ENV_CREATE ioctl failed"}, 
    { "8", "Command executed by vzctl exec returned non-zero exit code"}, 
    { "9", "Container is locked by another vzctl invocation"}, 
    { "10", "Global OpenVZ configuration file vz.conf(5) not found"}, 
    { "11", "A vzctl helper script file not found"}, 
    { "12", "Permission denied"}, 
    { "13", "Capability setting failed"}, 
    { "14", "Container configuration file ctid.conf(5) not found"}, 
    { "15", "Timeout on vzctl exec"}, 
    { "16", "Error during vzctl suspend"}, 
    { "17", "Error during vzctl resume"}, 
    { "18", "Error from setluid() syscall"}, 
    { "20", "Invalid command line parameter"}, 
    { "21", "Invalid value for command line parameter"}, 
    { "22", "Container root directory (VE_ROOT) not set"}, 
    { "23", "Container private directory (VE_PRIVATE) not set"}, 
    { "24", "Container template directory (TEMPLATE) not set"}, 
    { "28", "Not all required UBC parameters are set, unable to start container"}, 
    { "29", "OS template is not specified, unable to create container"}, 
    { "31", "Container not running"}, 
    { "32", "Container already running"}, 
    { "33", "Unable to stop container"}, 
    { "34", "Unable to add IP address to container"}, 
    { "40", "Container not mounted"}, 
    { "41", "Container already mounted"}, 
    { "43", "Container private area not found"}, 
    { "44", "Container private area already exists"}, 
    { "46", "Not enough disk space"}, 
    { "47", "Bad/broken container (/sbin/init or /bin/sh not found)"}, 
    { "48", "Unable to create a new container private area"}, 
    { "49", "Unable to create a new container root area"}, 
    { "50", "Unable to mount container"}, 
    { "51", "Unable to unmount container"}, 
    { "52", "Unable to delete a container"}, 
    { "53", "Container private area not exist"}, 
    { "60", "vzquota on failed"}, 
    { "61", "vzquota init failed"}, 
    { "62", "vzquota setlimit failed"}, 
    { "63", "Parameter DISKSPACE not set"}, 
    { "64", "Parameter DISKINODES not set"}, 
    { "65", "Error setting in-container disk quotas"}, 
    { "66", "vzquota off failed"}, 
    { "67", "ugid quota not initialized"}, 
    { "71", "Incorrect IP address format"}, 
    { "74", "Error changing password"}, 
    { "78", "IP address already in use"}, 
    { "79", "Container action script returned an error"}, 
    { "82", "Config file copying error"}, 
    { "86", "Error setting devices (--devices or --devnodes)"}, 
    { "89", "IP address not available"}, 
    { "91", "OS template not found"}, 
    { "99", "Ploop is not supported by either the running kernel or vzctl."}, 
    { "100", "Unable to find container IP address"}, 
    { "104", "VE_NETDEV ioctl error"}, 
    { "105", "Container start disabled"}, 
    { "106", "Unable to set iptables on a running container"}, 
    { "107", "Distribution-specific configuration file not found"}, 
    { "109", "Unable to apply a config"}, 
    { "129", "Unable to set meminfo parameter"}, 
    { "130", "Error setting veth interface"}, 
    { "131", "Error setting container name"}, 
    { "133", "Waiting for container start failed"}, 
    { "139", "Error saving container configuration file"}, 
    { "148", "Error setting container IO parameters (ioprio)"}, 
    { "150", "Ploop image file not found"}, 
    { "151", "Error creating ploop image"}, 
    { "152", "Error mounting ploop image"}, 
    { "153", "Error unmounting ploop image"}, 
    { "154", "Error resizing ploop image"}, 
    { "155", "Error converting container to ploop layout"}, 
    { "156", "Error creating ploop snapshot"}, 
    { "157", "Error merging ploop snapshot"}, 
    { "158", "Error deleting ploop snapshot"}, 
    { "159", "Error switching ploop snapshot"}, 
    { "166", "Error compacting ploop image"}, 
    { "167", "Error listing ploop snapsots"} 
}; 

И сгенерировать массив ...

System.out.println(" {"); 
for (int i = 0; i < errorcodesArray.length; i++) { 
    System.out.print("  { \""); 
    System.out.print(errorcodesArray[i][0]); 
    System.out.print("\", \""); 
    System.out.print(errorcodesArray[i][1]); 
    System.out.print("\"}"); 
    if (i + 1 < errorcodesArray.length) { 
    System.out.print(","); 
    } 
    System.out.println(); 
} 
System.out.println(" };"); 
+0

Мне нравится второй способ, вы ввели все эти значения вручную? – user2484067

+0

Конечно ... но я просто написал вам небольшой генератор кода. –

+0

Спасибо тонну! Это так полезно. – user2484067

1

Для этого, вероятно, следует использовать HashMap

0

Я предлагаю вам использовать HashMap вместо HashMap < Целое, строка>. Ключ предназначен для кода ошибки, а значение - для сообщения об ошибке.

Это полезно для заполнения сообщения об ошибке для данного кода ошибки. Если вы используете String [] [], сообщение об ошибке заполнения для данного кода ошибки не так просто.

HashMap ==> http://docs.oracle.com/javase/6/docs/api/java/util/HashMap.html?is-external=true

Если 2d типа массив String [] [] необходимо, то вы можете попробовать с помощью следующего кода для преобразования 1D в 2D массив.

//2D string to be converted. 
    String[][] convertedArray = new String[errorcodes.length][]; 

    for(int i=0, len = convertedArray.length;i<len;i++) 
    { 
     convertedArray[i] = errorcodes[i].split("\\|"); 
    } 
    //Print the 2D array in console 
    System.out.println(Arrays.deepToString(convertedArray)); 

Возьмите образец данных, например, выход в консоли будет выглядеть следующим образом:

[[1, Failed to set a UBC parameter], [2, Failed to set a fair scheduler parameter], [3, Generic system error], [5, The running kernel is not an OpenVZ kernel (or some OpenVZ modules are not loaded)], [6, Not enough system resources], [7, ENV_CREATE ioctl failed], [8, Command executed by vzctl exec returned non-zero exit code], [9, Container is locked by another vzctl invocation], [10, Global OpenVZ configuration file vz.conf(5) not found], [11, A vzctl helper script file not found], [12, Permission denied], [13, Capability setting failed], [14, Container configuration file ctid.conf(5) not found], [15, Timeout on vzctl exec], [16, Error during vzctl suspend], [17, Error during vzctl resume], [18, Error from setluid() syscall], [20, Invalid command line parameter], [21, Invalid value for command line parameter], [22, Container root directory (VE_ROOT) not set], [23, Container private directory (VE_PRIVATE) not set], [24, Container template directory (TEMPLATE) not set], [28, Not all required UBC parameters are set, unable to start container], [29, OS template is not specified, unable to create container], [31, Container not running], [32, Container already running], [33, Unable to stop container], [34, Unable to add IP address to container], [40, Container not mounted], [41, Container already mounted], [43, Container private area not found], [44, Container private area already exists], [46, Not enough disk space], [47, Bad/broken container (/sbin/init or /bin/sh not found)], [48, Unable to create a new container private area], [49, Unable to create a new container root area], [50, Unable to mount container], [51, Unable to unmount container], [52, Unable to delete a container], [53, Container private area not exist], [60, vzquota on failed], [61, vzquota init failed], [62, vzquota setlimit failed], [63, Parameter DISKSPACE not set], [64, Parameter DISKINODES not set], [65, Error setting in-container disk quotas], [66, vzquota off failed], [67, ugid quota not initialized], [71, Incorrect IP address format], [74, Error changing password], [78, IP address already in use], [79, Container action script returned an error], [82, Config file copying error], [86, Error setting devices (--devices or --devnodes)], [89, IP address not available], [91, OS template not found], [99, Ploop is not supported by either the running kernel or vzctl.], [100, Unable to find container IP address], [104, VE_NETDEV ioctl error], [105, Container start disabled], [106, Unable to set iptables on a running container], [107, Distribution-specific configuration file not found], [109, Unable to apply a config], [129, Unable to set meminfo parameter], [130, Error setting veth interface], [131, Error setting container name], [133, Waiting for container start failed], [139, Error saving container configuration file], [148, Error setting container IO parameters (ioprio)], [150, Ploop image file not found], [151, Error creating ploop image], [152, Error mounting ploop image], [153, Error unmounting ploop image], [154, Error resizing ploop image], [155, Error converting container to ploop layout], [156, Error creating ploop snapshot], [157, Error merging ploop snapshot], [158, Error deleting ploop snapshot], [159, Error switching ploop snapshot], [166, Error compacting ploop image], [167, Error listing ploop snapsots]] 
0

Вы можете создать 2D массив прямо из инициализации, вместо массива 1D все вместе, или вы может CONVER массив 1D к 2D массива, как это (с помощью разделения команды и итерация массива 1D):

String String[][] errorCodes = 
        new String[errorcodes.length][errorcodes[0].split("|").length]; 

for (int i = 0; i < errorcodes.length; i++) 
    errorCodes[i] = errorcodes[i].split("|"); 

по какой-то причине, это не работает. Это дает странный результат. Однако я сделал это раньше, и это сработало. Итак, идея есть.

Смежные вопросы