> Java > java지도 시간 > 본문

자바 NoSuchElementException

PHPz
풀어 주다: 2024-08-30 16:13:18
원래의
948명이 탐색했습니다.

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();
}  }
로그인 후 복사

출력:

자바 NoSuchElementException

이 프로그램에서는 해시 세트가 먼저 생성되고 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();
}  }
로그인 후 복사

출력:

자바 NoSuchElementException

이 프로그램에서는 해시 테이블이 먼저 생성되고 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());
}
}  }
로그인 후 복사

요소 유무를 확인하기 위해 기존 프로그램에 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());
}
}
로그인 후 복사

출력:

자바 NoSuchElementException

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.

자바 NoSuchElementException

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 중국어 웹사이트의 기타 관련 기사를 참조하세요!

관련 라벨:
원천:php
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!