我正在編寫一個程序,該程序將要求用戶輸入的第一個9
數字的ISBN編號(d1d2d3d4d5d6d7d8d9
),然後用10
打印出該編號基於下述等式個數位:字符串長度未正確打印,前面爲0
(d1 × 1 + d2 × 2 + d3 × 3 + d4 × 4 + d5 × 5 + d6 × 6 + d7 × 7 + d8 × 8 + d9 × 9)%11)
如果校驗10
,最後一位數字是根據該問題表示爲X
。如果不是,最後一個數字將被添加到ISBN上。除了當用戶輸入整數以0開頭時,我的程序工作。
例
輸入:113601267
輸出:113601267
例
輸入:013032342
輸出: 「這是一個無效的ISBN條目」
這裏是我的代碼:
int ISBN, r, i;
String st;
Scanner keyboard;
keyboard = new Scanner(System.in);
System.out.println("Please enter the first 9 digits of your ISBN number:");
ISBN = keyboard.nextInt();
st = ("" + ISBN);
if (st.length() == 9){
r = (st.charAt(0) * 1 + st.charAt(1) * 2 + st.charAt(2) * 3 + st.charAt(3) * 4 + st.charAt(4) * 5 + st.charAt(5) * 6 + st.charAt(6) * 7 + st.charAt(7) * 8 + st.charAt(8) * 9);
if (r % 11 == 10){
System.out.println("Your ISBN Number is: " + ISBN + "X");
}
else {
System.out.println(st);
i = (ISBN * 10) + (r % 11);
System.out.println("Your ISBN Number is: " + i);
}
}
else {
System.out.println("This is an invalid ISBN entry!");
}
哪兒了我搞砸了,或者是怎麼回事?
you're要求的'int'所以你得到的'int'。一個數字不關心前導零,並將它們分開。你可以使用'keyboard.nextLine()'或'keyboard.next()'來開始。 – SomeJavaGuy
我可以,但在它的問題說:編寫一個程序,提示用戶輸入前9位數字,並顯示包括前導零的10位ISBN, 。 **您的程序應讀取輸入爲整數** – bordia
您的ISBN是一個字符串而不是數字。領先的'0'事項,而一個數字將放棄這些。你應該用'scanner.next()'將它作爲一個字符串讀取,而不是將它轉換爲數字,然後返回到String中。 –