我正在尝试编写一个程序,要求用户输入一个十位数字,然后将每个数字存储在一个数组中。
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);
}
}
谁能告诉我哪里出错了?
答案 0 :(得分: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]
答案 1 :(得分: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]);
}
}
}