简体   繁体   English

使用 for 循环在 java 中打印 integer 数组,但第一个元素始终为零

[英]Printing an integer array in java using for loop, but the first element is always zero

I have been trying for hours to change a user inputted string of numbers into an integer, then create and print an integer array with those integers.几个小时以来,我一直在尝试将用户输入的数字字符串更改为 integer,然后使用这些整数创建并打印 integer 数组。 I finally got it, but the first element of the printed array is always zero.我终于明白了,但打印数组的第一个元素始终为零。 I don't know how to fix it.我不知道如何解决它。 I feel like it is really simple, but I am exhausted and am getting stuck on the easiest things.我觉得这真的很简单,但我已经筋疲力尽,而且卡在了最简单的事情上。 Does anyone know what is wrong?有谁知道出了什么问题? I'll put my code below.我会把我的代码放在下面。

String stringNum = input.nextLine();
int size = stringNum.length();
int[] myArray = new int[size];

for (int a : myArray) {
    System.out.print(a);
    System.out.print(" ");
    for (int i = 0; i < size; i++) {
        char n = stringNum.charAt(i);
        int intNum = Character.getNumericalValue(n);
        myArray[i] = intNum;
    }
}

// input: 12345 // output: 0 2 3 4 5 // 输入:12345 // output:0 2 3 4 5

You have mixed up printing the array and populating the array.您混淆了打印数组和填充数组。

First, parse the input string and populate the array首先,解析输入字符串并填充数组

String stringNum = input.nextLine();
int size = stringNum.length();
int[] myArray = new int[size];

for (int i = 0; i < size; i++) {
    char n = stringNum.charAt(i);
    int intNum = Character.getNumericalValue(n);
    myArray[i] = intNum;
}

Then print the elements,然后打印元素,

for (int a : myArray) {
    System.out.print(a);
    System.out.print(" ");
}

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

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