我正在尝试编写一个程序,要求用户输入十位数,然后将每个位数存储在数组中。

public class checksum {

public static void main(String[] args) {

    int david[] = new int[10];
    System.out.println("Enter your 10 digit number: ");
    Scanner scan = new Scanner(System.in);

    for (int i = 0; i < david.length; i++) {

        david[i] = scan.nextInt();
    }

    System.out.println(david);

}


}

谁能告诉我我要去哪里错了?

最佳答案

将其读取为String,然后使用String.charAt填充数组

    int david[] = new int[10];
    System.out.println("Enter your 10 digit number: ");
    Scanner scan = new Scanner(System.in);
    String str = scan.next();
    if (str.length() < david.length) {
        System.out.println("invalid number");
    }
    for (int i = 0; i < david.length; i++) {

        david[i] = Character.digit(str.charAt(i), 10);
    }
    System.out.println(Arrays.toString(david));


输出:

Enter your 10 digit number:
1234567890
[1, 2, 3, 4, 5, 6, 7, 8, 9, 0]

关于java - 如何用十位数字填充数组,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/12978517/

10-12 21:48