如何将第一个数字(0)映射为数组中的Int?

时间:2017-10-13 16:28:36

标签: java

我正在尝试打破一个int值并将其保存为数组,我尝试使用此方法,它工作正常,除非第一个数字为零时,它将其保存为1而不是0.如何解决此问题?

int k2CombinedEnc = in.nextInt();
int[] k2Enc = Integer.toString(k2CombinedEnc).chars().map(c -> c-='0').toArray(); 
for(int element: k2Enc) {
    System.out.println("encrypted ciphertext is" + element);
}

示例输出:

0010101010
encrypted ciphertext is1
encrypted ciphertext is0
encrypted ciphertext is1
encrypted ciphertext is0
encrypted ciphertext is1
encrypted ciphertext is0
encrypted ciphertext is1
encrypted ciphertext is0

2 个答案:

答案 0 :(得分:3)

您正在以整数形式读取值。所有前导零都被剥离,因为010只是10

改为以字符串形式阅读,你应该没问题。

String k2CombinedEnc = in.nextLine();
int[] k2Enc = k2CombinedEnc.chars().map(c -> c-='0').toArray(); 

for(int element: k2Enc) {
    System.out.println("encrypted ciphertext is" + element);
}

注意:考虑使用Character.digit方法而不是减去零:

int[] k2Enc = k2CombinedEnc.chars().map(c -> Character.digit(c, 10)).toArray(); 

答案 1 :(得分:0)

您也可以直接处理加密的密码字符串的字节。

String k2CombinedEnc = in.nextLine();
byte[] encodedBytes = k2CombinedEnc.getBytes(StandardCharsets.US_ASCII)
System.out.println("encrypted ciphertext is: ");
int i = 0;
for(byte element : encodedBytes) {
    System.out.println(" byte " + i++ + ": " + Integer.toHexString(element));
}
相关问题