Java中Enumeration中的nextElement方法、NamingEnumeration中的next方法等都會拋出NoSuchElementException異常。它表示枚舉中沒有其他元素了。該異常是RuntimeException異常的子類,並實作了Serialized介面。除了Enumeration之外,還有一些其他類別會拋出此異常。以下是不同的類別及其方法。
開始您的免費軟體開發課程
網頁開發、程式語言、軟體測試及其他
- StringTokenizer::nextElement()
- 枚舉::nextElement()
- 迭代器::next()
- NamingEnumeration::next()
NoSuchElementException 的語法、工作方式、建構子和範例將在以下部分中解釋。
聲明:
以下是 NoSuchElementException 的聲明。
public class NoSuchElementExceptionextends RuntimeException
NoSuchElementException 在 Java 中如何運作?
眾所周知,異常是程式執行過程中發生的錯誤。程式被終止,並且當拋出異常時,導致異常的行之後的程式碼行將不會被執行。在不同的情況下會拋出NosuchElementException。他們是:
- 在執行時期對空枚舉物件呼叫 Enumeration 類別的 nextElement( ) 方法,或目前位置為 Enumeration end 時,會拋出 NosuchElementException。
- 在運行時在空枚舉物件上呼叫 StringTokenizer 類別的 nextElement( ) 或 nextToken() 方法或目前位置為 StringTokenizerend 時拋出 NosuchElementException。
- 在執行時在空 Iterator 物件上呼叫 Iterator 類別的 next( ) 方法或目前位置為 Iterator end 時拋出 NosuchElementException。
- 在執行時,在空 ListIterator 物件上呼叫 ListIterator 類別的 next( ) 方法時,或當前位置為 ListIteratorend 時,會拋出 NosuchElementException。
- 在執行時,在空 ListIterator 物件上呼叫 ListIterator 類別的 previous ( ) 方法,或當前位置為 ListIteratorstart 時,會拋出 NosuchElementException。
建構子
以下是NoSuchElementException的兩個建構子
- NoSuchElementException(): NoSuchElementException 將在不提供任何錯誤訊息或通知作為字串的情況下構造。
- NoSuchElementException(Stringst): NoSuchElementException 將被建構,以字串 st 的形式提供錯誤訊息或通知。這用於稍後借助 getMessage 方法進行檢索。包含錯誤的類別名稱將出現在字串 st. 中
Java NoSuchElementException 範例
讓我們來看看一些在 Java 中拋出 NoSuchElementException 的範例程式。
範例#1
Java 程式拋出 NoSuchElementException,因為 HashSet 中沒有元素。
代碼:
import java.util.HashSet; import java.util.Set; //class public class NoExample { //main method public static void main(String[] args) { //create an object for set s Set s = new HashSet(); //select the next element s.iterator().next(); } }
輸出:
在此程式中,先建立一個雜湊集,然後使用 next() 方法選擇集合中的下一個元素。由於集合中沒有元素,因此拋出 NoSuchElementException。為了避免這種情況,可以在迭代集合之前進行檢查,如下所示。
import java.util.HashSet; import java.util.Iterator; import java.util.Set; //class public class NoExample { //main method public static void main(String[] args) { Set e = new HashSet(); Iterator it = e.iterator(); //checks whether any element is present while(it.hasNext()) { System.out.println(it.next()); } } }
為了檢查元素是否存在,在現有程式中加入了 while 迴圈和迭代器。如果執行這段程式碼,可以看到沒有拋出例外。
範例#2
由於 HashTable 中沒有元素而拋出 NoSuchElementException 的 Java 程式
代碼:
import java.util.Hashtable; //class public class NoExample { //main method public static void main(String[] args) { //create an object for hashtable s Hashtable s = new Hashtable(); //select the next element s.elements().nextElement(); } }
輸出:
在此程式中,先建立一個雜湊表,然後使用 nextElement() 方法選擇表中的下一個元素。由於表中沒有元素,因此拋出 NoSuchElementException。為了避免這種情況,可以在迭代表之前進行檢查,如下所示。
import java.util.Hashtable; import java.util.Iterator; import java.util.Set; //class public class NoExample { //main method public static void main(String[] args) { //create an object for hashtable s Hashtable s = new Hashtable(); Set<string>k = s.keySet(); Iterator<string>i = k.iterator(); while (i.hasNext()) { System.out.println(i.next()); } } }</string></string>
為了檢查元素是否存在,在現有程式中加入了 while 迴圈、集合和迭代器。如果執行這段程式碼,可以看到沒有拋出例外。
範例#3
Java 程式拋出 NoSuchElementException,因為 StringTokenizer 和 Enumeration 中沒有元素。
代碼:
import java.util.Enumeration; import java.util.Hashtable; import java.util.StringTokenizer; //class public class NoExample { private final static int el = 2; //main method public static void main(String[] args) { //declare a string String sn= "Happy Days never ends"; Hashtable s= new Hashtable(el); Enumeration t = s.elements(); //create an object for StringTokenizer StringTokenizer st = new StringTokenizer(sn, " "); //Print the tokens System.out.println(st.nextToken()); System.out.println(st.nextToken()); System.out.println(st.nextToken()); System.out.println(st.nextToken()); System.out.println(st.nextToken()); st.nextToken(); st.nextElement(); System.out.println(t.nextElement()); System.out.println(t.nextElement()); } }
輸出:
In this program, a StringTokenizer is created first, and tokens are selected five times. As there are only four tokens, NoSuchElementException is thrown. In order to avoid this, a check can be given before iterating the Tokenizeras shown below.
import java.util.Enumeration; import java.util.Hashtable; import java.util.StringTokenizer; //class public class NoExample { private final static int el = 2; //main method public static void main(String[] args) { //declare a string String sn= "Happy Days never ends"; Hashtable s= new Hashtable(el); Enumeration t = s.elements(); //create an object for StringTokenizer StringTokenizer st = new StringTokenizer(sn, " "); while(st.hasMoreTokens()) { System.out.println(st.nextToken()); } } }
In order to check the presence of elements, a while loop is added to the existing program. If this code is executed, it can be seen that no exceptions are thrown.
Conclusion
NoSuchElementException is an exception that is thrown when there are no elements retrieved on calling the method next( ) and nextElement( ) in classes Iterator, StringTokenizer, Enumeration and NamingEnumeration. In this article, different aspects such as the declaration, working, constructors, and examples of NoSuchElementException is explained in detail.
以上是Java NoSuchElementException的詳細內容。更多資訊請關注PHP中文網其他相關文章!

JVM'SperformanceIsCompetitiveWithOtherRuntimes,operingabalanceOfspeed,安全性和生產性。 1)JVMUSESJITCOMPILATIONFORDYNAMICOPTIMIZAIZATIONS.2)c提供NativePernativePerformanceButlanceButlactsjvm'ssafetyFeatures.3)

JavaachievesPlatFormIndependencEthroughTheJavavIrtualMachine(JVM),允許CodeTorunonAnyPlatFormWithAjvm.1)codeisscompiledIntobytecode,notmachine-specificodificcode.2)bytecodeisisteredbytheybytheybytheybythejvm,enablingcross-platerssectectectectectross-eenablingcrossectectectectectection.2)

TheJVMisanabstractcomputingmachinecrucialforrunningJavaprogramsduetoitsplatform-independentarchitecture.Itincludes:1)ClassLoaderforloadingclasses,2)RuntimeDataAreafordatastorage,3)ExecutionEnginewithInterpreter,JITCompiler,andGarbageCollectorforbytec

JVMhasacloserelationshipwiththeOSasittranslatesJavabytecodeintomachine-specificinstructions,managesmemory,andhandlesgarbagecollection.ThisrelationshipallowsJavatorunonvariousOSenvironments,butitalsopresentschallengeslikedifferentJVMbehaviorsandOS-spe

Java實現“一次編寫,到處運行”通過編譯成字節碼並在Java虛擬機(JVM)上運行。 1)編寫Java代碼並編譯成字節碼。 2)字節碼在任何安裝了JVM的平台上運行。 3)使用Java原生接口(JNI)處理平台特定功能。儘管存在挑戰,如JVM一致性和平台特定庫的使用,但WORA大大提高了開發效率和部署靈活性。

JavaachievesPlatFormIndependencethroughTheJavavIrtualMachine(JVM),允許Codetorunondifferentoperatingsystemsswithoutmodification.thejvmcompilesjavacodeintoplatform-interploplatform-interpectentbybyteentbytybyteentbybytecode,whatittheninternterninterpretsandectectececutesoneonthepecificos,atrafficteyos,Afferctinginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginging

JavaispoperfulduetoitsplatFormitiondence,對象與偏見,RichstandardLibrary,PerformanceCapabilities和StrongsecurityFeatures.1)Platform-dimplighandependectionceallowsenceallowsenceallowsenceallowsencationSapplicationStornanyDevicesupportingJava.2)

Java的頂級功能包括:1)面向對象編程,支持多態性,提升代碼的靈活性和可維護性;2)異常處理機制,通過try-catch-finally塊提高代碼的魯棒性;3)垃圾回收,簡化內存管理;4)泛型,增強類型安全性;5)ambda表達式和函數式編程,使代碼更簡潔和表達性強;6)豐富的標準庫,提供優化過的數據結構和算法。


熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

SAP NetWeaver Server Adapter for Eclipse
將Eclipse與SAP NetWeaver應用伺服器整合。

SublimeText3 英文版
推薦:為Win版本,支援程式碼提示!

SecLists
SecLists是最終安全測試人員的伙伴。它是一個包含各種類型清單的集合,這些清單在安全評估過程中經常使用,而且都在一個地方。 SecLists透過方便地提供安全測試人員可能需要的所有列表,幫助提高安全測試的效率和生產力。清單類型包括使用者名稱、密碼、URL、模糊測試有效載荷、敏感資料模式、Web shell等等。測試人員只需將此儲存庫拉到新的測試機上,他就可以存取所需的每種類型的清單。

SublimeText3 Mac版
神級程式碼編輯軟體(SublimeText3)

Safe Exam Browser
Safe Exam Browser是一個安全的瀏覽器環境,安全地進行線上考試。該軟體將任何電腦變成一個安全的工作站。它控制對任何實用工具的訪問,並防止學生使用未經授權的資源。