亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

是否可以將 try 與資源和輸入流一起使用?

是否可以將 try 與資源和輸入流一起使用?

慕容森 2023-08-04 15:36:01
Scanner sc = new Scanner(System.in)當使用資源實現 try 時,我通過try 語句的 inside ()創建一個 Scanner 對象。在 try 塊中,我提示用戶輸入一個數值,通過讀取它sc.nextLine()并將parseDouble其轉換為方法。如果最初輸入的值無效,我會利用 do-while 循環重新提示用戶輸入值。但是,如果用戶輸入無效值,則輸入流將關閉NumberFormatException并被捕獲,但在 do-while 循環的第二次迭代期間,會拋出“未找到行”NoSuchElementException,并且由于“流已關閉”java.lang.NoSuchElementException 異常而被拋出。 io.IOException。有沒有辦法在利用資源嘗試時規避這個問題?<?xml version="1.0" encoding="utf-8"?>    <androidx.constraintlayout.widget.ConstraintLayout        xmlns:android="http://schemas.android.com/apk/res/android"        xmlns:app="http://schemas.android.com/apk/res-auto"        xmlns:tools="http://schemas.android.com/tools"        android:layout_width="match_parent"        android:layout_height="match_parent"        android:orientation="horizontal"        android:padding="16dp">            <LinearLayout                android:id="@+id/a1"                android:layout_width="0dp"                app:layout_constraintWidth_percent=".48"                android:layout_height="0dp"                app:layout_constraintHeight_percent=".3"                android:background="@drawable/blacksquare"                app:layout_constraintStart_toStartOf="parent"                app:layout_constraintTop_toTopOf="parent"                android:padding="8dp"                android:orientation="horizontal">            </LinearLayout>            <LinearLayout                android:id="@+id/a2"                android:layout_width="0dp"                android:layout_height="0dp"                app:layout_constraintWidth_percent=".48"                app:layout_constraintHeight_percent=".3"                android:background="@drawable/blacksquare"                app:layout_constraintEnd_toEndOf="parent"                app:layout_constraintTop_toTopOf="parent"                android:padding="8dp"                android:orientation="horizontal">            </LinearLayout>    </androidx.constraintlayout.widget.ConstraintLayout>
查看完整描述

1 回答

?
慕桂英3389331

TA貢獻2036條經驗 獲得超8個贊

您不應該將 try-with-resource 與您自己沒有打開的資源一起使用,尤其是 with ,System.in它永遠不應該被應用程序關閉。


除此之外,您應該更喜歡事先測試條件,而不是捕獲異常。此外,盡量避免代碼重復,您最終會得到一個更簡單的解決方案:


public static void main(String[] args) {

? ? Scanner sc = new Scanner(System.in).useDelimiter("\\R");

? ? System.out.print("Enter first numeric value: ");

? ? double d1 = getDouble(sc);

? ? System.out.print("Enter second numeric value: ");

? ? double d2 = getDouble(sc);

? ? System.out.print("Choose an operation (+ - * /): ");

? ? while(!sc.hasNext("[-+*/]")) {

? ? ? System.out.println(sc.next()+" is not a valid operation");

? ? }

? ? String operation = sc.next();


? ? double result;

? ? switch (operation) {

? ? ? ? case "+": result = d1 + d2; break;

? ? ? ? case "-": result = d1 - d2; break;

? ? ? ? case "*": result = d1 * d2; break;?

? ? ? ? case "/": result = d1 / d2; break;

? ? ? ? default:

? ? ? ? ? ? throw new AssertionError("should not happen due to pretest");

? ? }

? ? System.out.println(d1+operation+d2);

? ? System.out.println("The answer is " + result);

}? ??

private static double getDouble(Scanner sc) {

? ? while(!sc.hasNextDouble()) {

? ? ? ? System.out.println(sc.next()+" is not a number");

? ? }

? ? return sc.nextDouble();

}

該解決方案用于hasNextDouble()詢問掃描器下一個令牌是否具有雙精度格式,并且只有在確認的情況下,應用程序才會通過 獲取它nextDouble()。否則,它用于next()獲取無效令牌,該令牌同時服務于報告并將其從未處理的輸入中刪除。同樣,hasNext("[-+*/]")檢查輸入是否與支持的四個運算符之一匹配。


由于編譯器不知道現在只能出現四個有效輸入之一,因此我們必須在 的情況下放置一個拋出語句default,switch否則編譯器會說result可能尚未初始化。我們可以初始化result為默認值,但如果程序流程未按預期工作,最好有一個強信號,而不是將默認值打印為錯誤結果。


使用Scanner可配置的分隔符來決定令牌的構成,因此該解決方案使用useDelimiter("\\R")換行符作為分隔符,將每一行視為一個令牌,就像原始代碼一樣。因此該類Pattern對語法進行了完整的描述。


查看完整回答
反對 回復 2023-08-04
  • 1 回答
  • 0 關注
  • 144 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號