[英]Java exception error causing code to stop suddenly
我正在为 class 开发一个项目,一切正常,直到教授给我们的代码会提示用户“重做”代码,如果他们选择的话,它会出现这个错误,坦率地说,我很困惑。
我尝试将 sc.nextLine 更改为 a.hasNextLine 正如我在其他帖子中看到的那样,但它出现了一个错误,指出它需要是 boolean 然后说我不能使用下一个 doOver.trim() 代码boolean。
final static String TITLE = "ISBN-13 Generator!";
final static String CONTINUE_PROMPT = "\nDo this again? [y/n] ";
static Scanner input = new Scanner(System.in);
private static void process(Scanner sc, String args[]) {
boolean numberChecker;
String isbn;
do {
System.out.println("\nEnter the first 12 digits of an ISBN-13: ");
isbn = input.nextLine();
input.close();
isbn = isbn.trim();
numberChecker = true;
int s = 0;
do {
numberChecker = numberChecker && Character.isDigit(isbn.charAt(s));
s++;
} while (s < isbn.length() || numberChecker == false);
} while (isbn.length() != 12 & numberChecker == false);
int sum = 0;
int s = 0;
do {
if (s % 2 == 0) {
sum = sum + isbn.charAt(s) - 48;
} else {
sum = sum + 3 * (isbn.charAt(s) - 48);
}
s++;
} while (s < 12);
{
sum = 10 - (sum % 10);
if (sum == 10)
sum = 0;
}
System.out.println("Your ISBN is " + isbn + sum);
}
private static boolean doThisAgain(Scanner sc, String prompt) {
System.out.print(prompt);
String doOver = sc.nextLine();
return doOver.trim().equalsIgnoreCase("Y");
}
public static void main(String args[]) {
System.out.println("Welcome to " + TITLE);
Scanner sc = new Scanner(System.in);
do {
process(sc, args);
} while (doThisAgain(sc, CONTINUE_PROMPT));
sc.close();
System.out.println("Thank you for using the " + TITLE);
}
它应该显示“再次执行此操作?[y/n]”,您输入“y”以重新开始该过程并输入“n”以停止并让系统打印出来(“感谢您使用”+TITLE)
发生这种情况是因为您已经使用 line input.close(); 关闭了扫描仪实例;
只需注释掉或删除input.close(); 并且您的程序将按预期工作。
System.out.println("\nEnter the first 12 digits of an ISBN-13: ");
isbn = input.nextLine();
//input.close();
让我知道它是否有帮助::)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.