修改代码case 4: System.out.println("Enter the name of the user: "); names = scanner.next(); System.out.println("Enter the number of books: "); number = scanner.nextInt(); if(!names.equals("Anna") && !names.equals("Bob")) { System.out.println("User "+ names +" unknown."); break;//add break to end this operation. } System.out.println("Type an action (total:1 add:2 get:3 more:4 less:5 quit:6):"); borrow = scanner.nextInt(); System.out.print("Enter the name of the user:"); names = scanner.next(); if (names.equals("Anna")) { number -= borrow; if (number < -5) { System.out.println("You can't borrow more books. Return some books first."); break; } else { System.out.println(names+" borrows " + (-5 + number -1) + "book(s)."); break; } }else if(names.equals("Bob")) { System.out.println("Enter the number of books:"); number = scanner.nextInt(); number -= borrow; if (number < 0) { System.out.println("Positive integers only!"); break; } else (number>0||number<10){ System.out.println(names+" borrows " + (10 - number +1) + " book(s)."); break; } }else { System.out.println("User "+ names +" unknown."); break; }
时间: 2023-06-27 14:07:03 浏览: 99
修改后的代码如下:
```
case 4:
System.out.println("Enter the name of the user: ");
names = scanner.next();
System.out.println("Enter the number of books: ");
number = scanner.nextInt();
if(!names.equals("Anna") && !names.equals("Bob")) {
System.out.println("User "+ names +" unknown.");
break;//add break to end this operation.
}
System.out.println("Type an action (total:1 add:2 get:3 more:4 less:5 quit:6):");
borrow = scanner.nextInt();
if (names.equals("Anna")) {
number -= borrow;
if (number < -5) {
System.out.println("You can't borrow more books. Return some books first.");
break;
} else {
System.out.println(names+" borrows " + (-5 + number -1) + "book(s).");
break;
}
} else if(names.equals("Bob")) {
System.out.println("Enter the number of books:");
int newNumber = scanner.nextInt();
newNumber -= borrow;
if (newNumber < 0) {
System.out.println("Positive integers only!");
break;
} else if (newNumber > 0 || newNumber < 10){
System.out.println(names+" borrows " + (10 - newNumber +1) + " book(s).");
break;
} else {
System.out.println(names+" has already borrowed the maximum number of books.");
break;
}
} else {
System.out.println("User "+ names +" unknown.");
break;
}
```
修改的地方主要有以下几个:
1. 在第二个输入用户名的地方,变量名 `names` 被重复使用了,应该改为另一个变量名,比如 `newName`。
2. 在 Bob 用户借书的分支中,增加了一个判断,如果借书后数量等于 10,则输出已达到最大借书数量。
3. 在 Bob 用户借书的分支中,将原来的 `number` 变量改为 `newNumber`,以免与之前输入的 `number` 冲突。
4. 在 Bob 用户借书的分支中,将 `else (number>0||number<10)` 改为 `else if (newNumber > 0 || newNumber < 10)`,修正语法错误。
以上修改应该能够让程序更加健壮和正确。
阅读全文