英文:
Cannot take user input in main java method
问题
}
public static void main(String[] args) {
Scanner userInputs = new Scanner(System.in);
loadCurrencyCodes();
showCurrencies();
findMyCurrency();
System.out.print("Try again (Y/N): ");
String yesNo = userInputs.next();
}
}
Exception in thread "main" 尝试重新运行代码时,我从用户处获取y/n的输入时出现java.util.NoSuchElementException异常。
英文:
}
public static void main(String[] args) {
Scanner userInputs = new Scanner(System.in);
loadCurrencyCodes();
showCurrencies();
findMyCurrency();
System.out.print("Try again (Y/N): ");
String yesNo = userInputs.next();
}
}
Exception in thread "main" Try again (Y/N): java.util.NoSuchElementException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at CheckCurrencyCode.main(CheckCurrencyCode.java:69)
I'm attempting to take in an input of y/n from the user, when I run the code I get the above exception.
答案1
得分: 0
你应该在它的工作完成后关闭 userInput 对象:
System.out.print("再试一次(Y/N):");
String yesNo = userInputs.next();
userInputs.close();
英文:
You should close object userInput object when its work is over :
System.out.print("Try again (Y/N): ");
String yesNo = userInputs.next();
userInputs.close();
答案2
得分: 0
Sure, here's the translated code snippet:
您可以使用 try-with-resources 结构,它会自动处理流的关闭。
try (Scanner userInputs = new Scanner(System.in)) {
System.out.print("再试一次(Y/N):");
String yesNo = userInputs.next();
}
英文:
> You can use try with resource and it will automatically handle closing stream for you.
try(Scanner userInputs = new Scanner(System.in)){
System.out.print("Try again (Y/N): ");
String yesNo = userInputs.next();
}
专注分享java语言的经验与见解,让所有开发者获益!
评论