2 回答
TA贡献1839条经验 获得超15个赞
是的,您在此for循环中缺少增量器
for (int i=0; i <= s.length();) {
改成
for (int i=0; i <= s.length(); i++) {
我相信你不想要<=,也许只是<
所以
for (int i=0; i < s.length(); i++) {
顺便说一句,如果您调试代码,这很容易解决 - 一项基本技能 -
编辑
如果您有以下代码(和 s.length == 12)
for (int i=0; i < s.length(); i++) {
System.out.println("Enter the first 9 or 12 digits of an ISBN number. Enter QUIT to exit: ");
s = input.next();
}
然后它将执行 12 次。修复你的循环
TA贡献1846条经验 获得超7个赞
更新代码,因为我在这里实施了一些建议:
package lab05a;
import java.util.Scanner;
public class Lab05A {
public static void main(String[] args) {
// Input for s
Scanner input = new Scanner(System.in); // Create new scanner
System.out.println("Enter the first 9 or 12 digits of an ISBN number. Enter QUIT to exit: "); // our ever-lasting prompt
String s = input.next(); // declare string variable "s" and set it equal to next input from user.
String output10 = ""; // Declaring string output10
String output13 = ""; // Declaring string output13
// main while loop
while (!"QUIT".equalsIgnoreCase(s)) { //this will run as long as the program does not receive an input of "QUIT", not case sensitive.
char checkDigit;
char checkSum = '0';
if (s.length() == 9) { //if the length of the inputted string is 9 characters...
int sum = 0; // initialize sum variable
for (int i=0; i < s.length(); i++) {
sum = sum + ((s.charAt(i) - '0') * (i + 1));
}
if (sum % 11 == 10) {
checkDigit = 'X';
}
else {
checkDigit = (char) ('0' + (sum % 11));
}
output10 = output10 + "\n" + s + checkDigit;
System.out.println("Enter the first 9 or 12 digits of an ISBN number. Enter QUIT to exit: ");
s = input.next();
}
else if (s.length() == 12) {
int sum = 0;
for (int i=0; i < s.length(); i++) {
if (i % 2 == 0) {
sum = sum + (s.charAt(i) - '0');
}
else {
sum = sum + (s.charAt(i) - '0') * 3;
}
checkSum = (char) (10 - sum % 10);
if (checkSum == 10) {
checkSum = 0;
}
output13 = "\n" + output13 + s + checkSum;
System.out.println("Enter the first 9 or 12 digits of an ISBN number. Enter QUIT to exit: ");
s = input.next();
}
}
else if (!"QUIT".equalsIgnoreCase(s)) {
System.out.println(s + " is invalid input.");
System.out.println("Enter the first 9 or 12 digits of an ISBN number. Enter QUIT to exit: ");
s = input.next();
}
}
System.out.println("The 10 digit ISBNs are \n" + output10);
System.out.println("The 13 digit ISBNs are \n" + output13);
}
}
添加回答
举报