nextElement 메소드는 Enumeration의 Java에서 NoSuchElementException을 발생시키고 NamingEnumeration의 next 메소드 등을 발생시킵니다. 이는 열거에 더 이상 요소가 없음을 나타냅니다. 이 예외는 RuntimeException 예외의 하위 클래스이며 Serialized 인터페이스를 구현합니다. 열거형 외에도 이 예외를 발생시키는 다른 클래스가 있습니다. 다양한 클래스와 메소드는 다음과 같습니다.
무료 소프트웨어 개발 과정 시작
웹 개발, 프로그래밍 언어, 소프트웨어 테스팅 등
- StringTokenizer::nextElement()
- 열거::nextElement()
- 반복자::next()
- 이름 지정 열거형::next()
NoSuchElementException의 구문, 작업, 생성자 및 예는 다음 섹션에서 설명됩니다.
선언:
다음은 NoSuchElementException 선언입니다.
public class NoSuchElementExceptionextends RuntimeException
Java에서 NoSuchElementException은 어떻게 작동하나요?
아시다시피 예외는 프로그램 실행 중에 발생한 오류입니다. 프로그램이 종료되고, 예외가 발생하면 예외를 발생시킨 줄 다음의 코드 줄은 실행되지 않습니다. NosuchElementException이 발생하는 상황은 다양합니다. 그들은:
- anull 열거형 객체에 대해 Enumeration 클래스의 nextElement() 메소드를 호출하기 위해 런타임 중에 NosuchElementException이 발생하거나, 현재 위치가 Enumeration end입니다.
- NosuchElementException은 Null 열거 개체 또는 현재 위치 isStringTokenizerend에서 StringTokenizer 클래스의 nextElement( ) 또는 nextToken() 메서드를 호출할 때 런타임 중에 발생합니다.
- NosuchElementException은 Null Iterator 객체에서 Iterator 클래스의 next() 메서드를 호출하거나 현재 위치가 Iterator end인 경우 런타임 중에 발생합니다.
- NosuchElementException은 Null ListIterator 객체 또는 현재 위치 isListIteratorend에서 ListIterator 클래스의 next() 메서드를 호출할 때 런타임 중에 발생합니다.
- NosuchElementException은 Null ListIterator 객체 또는 현재 위치 isListIteratorstart에서 ListIterator 클래스의 이전 메서드( )를 호출할 때 런타임 중에 발생합니다.
건축자
다음은 NoSuchElementException의 두 생성자입니다
- NoSuchElementException(): NoSuchElementException은 오류 메시지나 알림을 문자열로 제공하지 않고 생성됩니다.
- NoSuchElementException(Stringst): NoSuchElementException은 문자열 st로 오류 메시지나 알림을 제공하는 구성됩니다. 이는 getMessage 메소드의 도움으로 나중에 검색하는 데 사용됩니다. 오류가 포함된 클래스 이름은 문자열 st에 표시됩니다.
Java NoSuchElementException의 예
Java에서 NoSuchElementException을 발생시키는 샘플 프로그램 중 일부를 살펴보겠습니다.
예시 #1
HashSet에 요소가 없기 때문에 NoSuchElementException을 발생시키는 Java 프로그램
코드:
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
StringTokenizer 및 Enumeration에 요소가 없기 때문에 NoSuchElementException을 발생시키는 Java 프로그램.
코드:
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.
위 내용은 자바 NoSuchElementException의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

javaachievesplatformincendenceThoughthehoughthejavavirtualmachine (JVM), hittoutModification.thejvmcompileSjavacodeIntOplatform-independentByTecode, whatitTengretsAndexeSontheSpecoS, toplacetSonthecificos, toacketSecificos

javaispowerfuldueToitsplatformincendence, 객체 지향적, RichandardLibrary, PerformanceCapabilities 및 StrongSecurityFeatures.1) Platform IndependenceAllowsApplicationStorunannyDevicesUpportingjava.2) 대상 지향적 프로그래밍 프로모션 Modulara

최고 Java 기능에는 다음이 포함됩니다. 1) 객체 지향 프로그래밍, 다형성 지원, 코드 유연성 및 유지 관리 가능성 향상; 2) 예외 처리 메커니즘, 시도 캐치-패치 블록을 통한 코드 견고성 향상; 3) 쓰레기 수집, 메모리 관리 단순화; 4) 제네릭, 유형 안전 강화; 5) 코드를보다 간결하고 표현력있게 만들기위한 AMBDA 표현 및 기능 프로그래밍; 6) 최적화 된 데이터 구조 및 알고리즘을 제공하는 풍부한 표준 라이브러리.

javaisnotentirelyplatformindent의 의존적 duetojvmvariationsandnativecodeintegration

TheJavavirtualMachine (JVM) isanabstractcomputingmachinecrucialforjavaexecutionasitsjavabytecode, "writeonce, runanywhere"기능을 가능하게합니다

javaremainsagoodlugageedueToitscontinuousevolutionandrobustecosystem.1) lambdaexpressionsenhancececeadeabilitys.2) Streamsallowforefficileddataprocessing, 특히 플레어로드 라트 웨이션

javaisgreatduetoitsplatform incendence, robustoopsupport, extensibraries 및 strongcommunity.1) platforminceptenceviajvmallowscodetorunonvariousplatforms.2) oopeatures inncapsulation, Nheritance, and Polymorphismenblularandscode.3)

Java의 5 가지 주요 특징은 다형성, Lambda Expressions, Streamsapi, 제네릭 및 예외 처리입니다. 1. 다형성을 사용하면 다른 클래스의 물체가 공통 기본 클래스의 물체로 사용될 수 있습니다. 2. Lambda 표현식은 코드를보다 간결하게 만듭니다. 특히 컬렉션 및 스트림을 처리하는 데 적합합니다. 3.StreamSapi는 대규모 데이터 세트를 효율적으로 처리하고 선언적 작업을 지원합니다. 4. 제네릭은 유형 안전 및 재사용 성을 제공하며 편집 중에 유형 오류가 잡히립니다. 5. 예외 처리는 오류를 우아하게 처리하고 신뢰할 수있는 소프트웨어를 작성하는 데 도움이됩니다.


핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

Video Face Swap
완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

인기 기사

뜨거운 도구

에디트플러스 중국어 크랙 버전
작은 크기, 구문 강조, 코드 프롬프트 기능을 지원하지 않음

PhpStorm 맥 버전
최신(2018.2.1) 전문 PHP 통합 개발 도구

SublimeText3 Linux 새 버전
SublimeText3 Linux 최신 버전

WebStorm Mac 버전
유용한 JavaScript 개발 도구

ZendStudio 13.5.1 맥
강력한 PHP 통합 개발 환경