Метод ByteBuffer getFloat () в Java с примерами
Метод getFloat () класса java.nio.ByteBuffer используется для чтения следующих четырех байтов в текущей позиции этого буфера, компоновки их в значение с плавающей запятой в соответствии с текущим порядком байтов, а затем увеличивает позицию на четыре.
Синтаксис:
публичный абстрактный поплавок getFloat ()
Возвращаемое значение: этот метод возвращает значение с плавающей запятой в текущей позиции буфера.
Исключение: этот метод вызывает исключение BufferUnderflowException, если в этом буфере осталось менее четырех байтов.
Ниже приведены примеры, иллюстрирующие метод getFloat ():
Examples 1:
// Java program to demonstrate // getFloat() method import java.nio.*; import java.util.*; public class GFG { public static void main(String[] args) { // Declaring the capacity of the ByteBuffer int capacity = 8 ; // Creating the ByteBuffer try { // creating object of ByteBuffer // and allocating size capacity ByteBuffer bb = ByteBuffer.allocate(capacity); // putting the double value in the bytebuffer bb.asFloatBuffer() .put( 12 .3f) .put( 28 .44f); // rewind the Bytebuffer bb.rewind(); // print the ByteBuffer System.out.println( "Original ByteBuffer: " ); for ( int i = 1 ; i <= capacity / 4 ; i++) System.out.print(bb.getFloat() + " " ); // rewind the Bytebuffer bb.rewind(); // Reads the Float at this buffer"s current position // using getFloat() method float value = bb.getFloat(); // print the float value System.out.println( "
Byte Value: " + value); // Reads the float at this buffer"s next position // using getFloat() method float value1 = bb.getFloat(); // print the float value System.out.print( "
Next Byte Value: " + value1); } catch (BufferUnderflowException e) { System.out.println( "
Exception Thrown : " + e); } } } |
Original ByteBuffer: 12.3 28.44 Byte Value: 12.3 Next Byte Value: 28.44
Examples 2:
// Java program to demonstrate // getFloat() method import java.nio.*; import java.util.*; public class GFG { public static void main(String[] args) { // Declaring the capacity of the ByteBuffer int capacity = 8 ; // Creating the ByteBuffer try { // creating object of ByteBuffer // and allocating size capacity ByteBuffer bb = ByteBuffer.allocate(capacity); // putting the double value in the bytebuffer bb.asFloatBuffer() .put( 12 .3f) .put( 28 .44f); // rewind the Bytebuffer bb.rewind(); // print the ByteBuffer System.out.println( "Original ByteBuffer: " ); for ( int i = 1 ; i <= capacity / 4 ; i++) System.out.print(bb.getFloat() + " " ); // rewind the Bytebuffer bb.rewind(); // Reads the Float at this buffer"s current position // using getFloat() method float value = bb.getFloat(); // print the float value System.out.println( "
Byte Value: " + value); // Reads the float at this buffer"s next position // using getFloat() method float value1 = bb.getFloat(); // print the float value System.out.println( "
Next Byte Value: " + value1); // Reads the float at this buffer"s next position // using getFloat() method float value2 = bb.getFloat(); } catch (BufferUnderflowException e) { System.out.println( "
there are fewer " + "than eight bytes remaining" + " in this buffer" ); System.out.println( "Exception Thrown : " + e); } } } |
Original ByteBuffer: 12.3 28.44 Byte Value: 12.3 Next Byte Value: 28.44 there are fewer than eight bytes remaining in this buffer Exception Thrown : java.nio.BufferUnderflowException
Ссылка: https://docs.oracle.com/javase/9/docs/api/java/nio/ByteBuffer.html#getFloat–
Метод getFloat (int index) java.nio.ByteBuffer используется для чтения четырех байтов по заданному индексу, составляя их в значение с плавающей запятой в соответствии с текущим порядком байтов.
Синтаксис:
общедоступный абстрактный поплавок getFloat (индекс int)
Параметры: этот метод принимает индекс в качестве параметра, который является индексом, из которого будет читаться байт.
Возвращаемое значение: этот метод возвращает значение с плавающей запятой по заданному индексу.
Исключение: этот метод вызывает исключение IndexOutOfBoundsException, если индекс отрицательный или не меньше предела буфера.
Ниже приведены примеры, иллюстрирующие метод getFloat (int index) :
Examples 1:
// Java program to demonstrate // getFloat() method import java.nio.*; import java.util.*; public class GFG { public static void main(String[] args) { // Declaring the capacity of the ByteBuffer int capacity = 8 ; // Creating the ByteBuffer try { // creating object of ByteBuffer // and allocating size capacity ByteBuffer bb = ByteBuffer.allocate(capacity); // putting the double value in the bytebuffer bb.asFloatBuffer() .put( 12 .3f) .put( 28 .44f); // rewind the Bytebuffer bb.rewind(); // print the ByteBuffer System.out.println( "Original ByteBuffer: " ); for ( int i = 1 ; i <= capacity / 4 ; i++) System.out.print(bb.getFloat() + " " ); // rewind the Bytebuffer bb.rewind(); // Reads the Float at this buffer"s current position // using getFloat() method float value = bb.getFloat( 0 ); // print the float value System.out.println( "
Byte Value: " + value); // Reads the float at this buffer"s next position // using getFloat() method float value1 = bb.getFloat( 4 ); // print the float value System.out.println( "
Next Byte Value: " + value1); } catch (IndexOutOfBoundsException e) { System.out.println( "
index is negative or smaller" + " than the buffer"s limit, " + "minus seven" ); System.out.println( "Exception Thrown : " + e); } } } |
Original ByteBuffer: 12.3 28.44 Byte Value: 12.3 Next Byte Value: 28.44
Examples 2:
// Java program to demonstrate // getFloat() method import java.nio.*; import java.util.*; public class GFG { public static void main(String[] args) { // Declaring the capacity of the ByteBuffer int capacity = 8 ; // Creating the ByteBuffer try { // creating object of ByteBuffer // and allocating size capacity ByteBuffer bb = ByteBuffer.allocate(capacity); // putting the double value in the bytebuffer bb.asFloatBuffer() .put( 12 .3f) .put( 28 .44f); // rewind the Bytebuffer bb.rewind(); // print the ByteBuffer System.out.println( "Original ByteBuffer: " ); for ( int i = 1 ; i <= capacity / 4 ; i++) System.out.print(bb.getFloat() + " " ); // rewind the Bytebuffer bb.rewind(); // Reads the Float at this buffer"s current position // using getFloat() method float value = bb.getFloat( 0 ); // print the float value System.out.println( "
Byte Value: " + value); // Reads the float at this buffer"s next position // using getFloat() method float value1 = bb.getFloat( 6 ); // print the float value System.out.println( "
Next Byte Value: " + value1); } catch (IndexOutOfBoundsException e) { System.out.println( "
index is negative or" + " smaller than the buffer"s " + "limit, minus seven" ); System.out.println( "Exception Thrown : " + e); } } } |
Original ByteBuffer: 12.3 28.44 Byte Value: 12.3 index is negative or smaller than the buffer"s limit, minus seven Exception Thrown : java.lang.IndexOutOfBoundsException
Ссылка: https://docs.oracle.com/javase/9/docs/api/java/nio/ByteBuffer.html#getFloat-int-
Вниманию читателя! Не переставай учиться сейчас. Ознакомьтесь со всеми важными концепциями Java Foundation и коллекций с помощью курса "Основы Java и Java Collections" по доступной для студентов цене и будьте готовы к работе в отрасли. Чтобы завершить подготовку от изучения языка к DS Algo и многому другому, см. Полный курс подготовки к собеседованию .