【问题标题】:JAVA ISBN-10 Number: Find 10th digit [closed]JAVA ISBN-10 编号:查找第 10 位 [关闭]
【发布时间】:2017-01-21 14:23:08
【问题描述】:

问题:

一个 ISBN-10 由 10 位数字组成:d1,d2,d3,d4,d5,d6,d7,d8,d9,d10。最后一位数字 d10 是校验和,由其他九位数字计算得出 以下公式:

(d1 * 1 + d2 * 2 + d3 * 3 + d4 * 4 + d5 * 5 + d6 * 6 + d7 * 7 + d8 * 8 + d9 * 9) % 11

如果校验和为 10,则根据 ISBN-10,最后一位数字表示为 X 习俗。

编写一个程序,提示用户输入前 9 位数字并显示 10 位数字 ISBN(包括前导零)。您的程序应将输入读取为整数。

以下是运行示例:

输入 ISBN 的前 9 位整数:013601267

ISBN-10 号码是 0136012671

我的密码:

import java.util.Scanner;

public class ISBN_Number {

    public static void main(String[] args) {
        Scanner s = new Scanner(System.in);

        int[] num = new int[9];

        System.out.println("Enter the first 9 digits of the an ISBN as integer: ");

        for (int i = 0; i < num.length; i++) {
            for (int j = 1; j < 10; j++) {
                num[i] = s.nextInt() * j;
            }
        }

        int sum = 0;
        for (int a = 0; a < 10; a++) {
            sum += num[a];
        }
        int d10 = (sum % 11);
        System.out.println(d10);

        if (d10 == 10) {
            System.out.println("The ISBN-10 number is " + num + "X");
        } else {
            System.out.println("The ISBN-10 number is" + num);
        }
    }
}

问题: 我是学习 java 的新手,因此我在尝试解决这个问题时遇到了麻烦。有人可以告诉我哪里出错了,因为我没有得到预期的结果。谢谢。

【问题讨论】:

  • 您正在尝试从Scanner...中读取 81 个整数...
  • 您介意详细说明我是如何这样做的吗?我对如何读取 81 个整数感到困惑。

标签: java arrays if-statement for-loop isbn


【解决方案1】:

nextInt() 消耗整个令牌013601267,而不仅仅是一个数字,这不是你的计划。一种更简单的方法是将其作为单个字符串使用,然后遍历字符:

String num = s.next();
int sum = 0;
for (int i = 1; i <= num.length(); ++i) {
    sum += (i * num.charAt(i - 1) - '0');
}

int d10 = (sum % 11);
if (d10 == 10) {
    System.out.println("The ISBN-10 number is " + num + "X");
} else {
    System.out.println("The ISBN-10 number is " + num + d10);
}

【讨论】:

    【解决方案2】:

    因为

     for (int i = 0; i < num.length; i++) {
            for (int j = 1; j < 10; j++) {
                num[i] = s.nextInt() * j;
            }
        }
    

    在这里,您的每个输入都将乘以 9 次

    喜欢当用户输入 2 然后 2 将像 (2*1)(2*2)(2*3) 所示相乘......所以这里是 num[0]== 18(2*9)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多