[英]How can I close a scanner that is inside of a loop?
這段代碼有效,但是我剩下的掃描器沒有關閉,當我嘗試關閉它時,它會導致連續循環。 我如何關閉該掃描儀而不導致連續循環。
這是我的代碼:
double startingAmount = 0;
//Asks how much money customer has to spend, and will re-ask if an invalid input is put in.
System.out.println("Please enter how much money you have to spend (enter -1 to shut down):");
int x = 1;
do {
try {
Scanner scanner = new Scanner(System.in);
startingAmount = scanner.nextDouble();
x = 2;
} catch (Exception e) {
System.out.println(
"Invalid input, please enter how much money you have to spend (enter -1 to shut down):");
}
} while (x == 1);
別。 在循環之前將其打開。 通常,您將在循環后關閉它,但是當它包裝System.in
您根本不應該將其關閉。
關閉IO流(這是System.in在鍵盤上的作用)始終是一個好主意,以消除潛在的資源泄漏,但是在這種特定情況下(作為控制台應用程序),您僅應關閉掃描儀(使用系統)。 in),當您知道自己已經完全完成時。 在您的情況下,它將在您的簡單應用程序結束時自動關閉。 關閉使用System.in的 掃描儀后 ,將無法在當前應用程序會話期間再次使用System.in 。
在do / while循環上方創建掃描儀實例。 在循環中進行操作不是一個好主意。
當前正在編寫代碼時,僅Scanner.nextDouble()方法需要try / catch 。 嘗試使用適當的Exceptions-最好使用InputMismatchException而不是Exception 。
最好將您的初始提示放在do / while循環開始時, 而無需重復提示。 允許catch塊僅指示無效條目。
在這里,使用do / while(true)或while(true){}可能比使用整數變量x然后代替x = 2;
更好x = 2;
使用break;
。 您使用int變量執行此操作的方式將正常工作,並且沒有任何問題,只要它滿足循環的條件並且在某個時候一定會退出相同的循環即可。 我只是使用while(true)和break來發現它更干凈; 像這樣簡單的事情。 當然,這只是基於意見,我們希望嘗試避免。
您應該放置scanner.nextLine();
在 catch代碼塊之后直接清除掃描程序緩沖區,因為nextDouble() (或nextByte() , nextShort() , nextInt() , nextLong() , nextFloat()等)不提供換行符。 這將消除在無效條目上的連續循環。
StackOverflow提供了許多有關如何實現工作的示例。 您只需要尋找它們。 即使將諸如“ 如何在Java控制台中提示用戶 ”之類的晦澀的東西放到Google中,也會產生大約400萬個結果。
Scanner
實現java.io.Closeable
接口。 因此,您可以使用try-with-resources構造實例化新的Scanner
實例。
如果確實需要在do/while
循環內創建Scanner
,則可以執行以下操作:
public static void main(String[] args) {
double startingAmount = 0;
//Asks how much money customer has to spend, and will re-ask if an invalid input is put in.
System.out.println("Please enter how much money you have to spend (enter -1 to shut down):");
int x = 1;
do {
try (Scanner scanner = new Scanner(System.in)) {
startingAmount = scanner.nextDouble();
x = 2;
}
} while (x == 1);
}
但是,最好使用try-with-resources創建一次掃描程序,然后在try塊內添加循環,這是一個更好的主意:
public static void main(String[] args) {
double startingAmount = 0;
//Asks how much money customer has to spend, and will re-ask if an invalid input is put in.
System.out.println("Please enter how much money you have to spend (enter -1 to shut down):");
int x = 1;
try (Scanner scanner = new Scanner(System.in)) {
do {
startingAmount = scanner.nextDouble();
x = 2;
} while (x == 1);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.