本文介绍了JAVA ISBN-10编号:第10位数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题:

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

An ISBN-10 consists of 10 digits: d1,d2,d3,d4,d5,d6,d7,d8,d9,d10. The last digit, d10, is a checksum,which is calculated from the other nine digits usingthe following formula:

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

如果校验和为10,则根据ISBN-10
约定,最后一位表示为X。

If the checksum is 10, the last digit is denoted as X according to the ISBN-10convention.

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

Write a program that prompts the user to enter the first 9 digits and displays the 10-digit ISBN (including leading zeros). Your program should read the input as an integer.

以下是示例运行:

输入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的新手,因此我很难设法弄清楚这个问题。有人可以告诉我我要去哪里错了,因为我没有得到预期的结果。谢谢。

ISSUE:I am new to learning java, hence I am having trouble trying to figure this question out. Can some tell me where I am going wrong because I am not getting the expected outcome. Thank you.

推荐答案

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

nextInt() consumes the entire token 013601267, not just a single digit, which was not your plan. A much easier approach could be to consume it as a single string and then iterate over the characters:

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

这篇关于JAVA ISBN-10编号:第10位数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 02:31