简体   繁体   English

为什么我的for循环没有为数组分配值?

[英]Why isn't my for loop that assigns values to arrays working?

I'm expecting the program to output all the digits entered, but it is only outputting the last digit in the number over and over again. 我希望程序输出所有输入的数字,但它只是一遍又一遍地输出数字中的最后一位数字。

import java.util.Scanner;
public class Example9 {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        //asks user to input the first 9 digits of an ISBN
        System.out.println("Enter first nine digits: ");
        int firstNine = input.nextInt();
        int[] digits = new int[9];
        int digitsLeft = firstNine;
        for(int i = digits.length - 1; i > 0; i--) {
            int digit = firstNine % 10;
            digitsLeft = (int) Math.floor(digitsLeft / 10);
            digits[i] = digit;
            System.out.println(digits[i]);
        }
    }
}
int digit = firstNine % 10;

must be 一定是

int digit = digitsLeft % 10;

Also, with i > 0 you will not add the first digit. 此外,如果i > 0您将不会添加第一个数字。 It must be i >= 0 . 它必须是i >= 0

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

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