0

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

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);

}

}

谁能告诉我哪里出错了?

4

2 回答 2

3

读取它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]
于 2012-10-19T16:33:16.110 回答
1

您已将读取的代码放入循环中,这将使控制台等待 10 个输入。您可以输入一次,然后打破数字。下面是代码

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);

    int number = scan.nextInt();

    for (int i = david.length - 1; i >= 0; i--) {
        david[i] = number%10;
        number /= 10;
    }

    for (int i = 0; i < david.length; i++) {
        System.out.print(david[i]);
    }

}
}
于 2012-10-19T16:33:16.307 回答