Java中的数组getFloat()方法

这个 JAVA朗,反思一下。大堆getFloat() 是Java中数组类的内置方法,用于将指定数组中给定索引处的元素作为Float返回。

null

语法 :

Array.getFloat(Object []array, int index)

参数: 此方法接受两个强制参数:

  • 数组: 要返回其索引的对象数组。
  • 索引: 给定数组的特定索引。返回给定数组中“index”处的元素。

返回值: 此方法以字节形式返回数组的元素。

例外情况: 此方法引发以下异常:

  • 空指针异常 –当数组为空时。
  • 非法数据异常 –当给定的对象数组不是数组时。
  • 数组下标越界异常 –如果给定索引不在数组大小的范围内。

注: Typecast不是必需的,因为返回类型是float。

下面的程序演示了Array类的getFloat()方法。

方案1 :

// Java code to demonstrate getFloat() method of Array class
import java.lang.reflect.Array;
public class GfG {
// main method
public static void main(String[] args)
{
// Declaring and defining a float array
float a[] = { 1 .0f, 2 .0f, 3 .0f };
// Traversing the array
for ( int i = 0 ; i < 3 ; i++) {
// Array.getBoolean() method
float x = Array.getFloat(a, i);
// Printing the values
System.out.print(x + " " );
}
}
}


输出 :

1.0 2.0 3.0 

方案2 :

// Java code to demonstrate getFloat() method of Array class
import java.lang.reflect.Array;
public class GfG {
// main method
public static void main(String[] args)
{
// Declaring and defining a float array
float a[] = { 1 .0f, 2 .0f, 3 .0f };
try {
float x = Array.getFloat(a, 4 );
}
catch (Exception e) {
System.out.println( "Exception : " + e);
}
}
}


输出 :

Exception : java.lang.ArrayIndexOutOfBoundsException

方案3 :

// Java code to demonstrate getFloat() method of Array class
import java.lang.reflect.Array;
public class GfG {
// main method
public static void main(String[] args)
{
// Declaring and defining a float array as null
float a[] = null ;
try {
float x = Array.getFloat(a, 4 );
}
catch (Exception e) {
System.out.println( "Exception : " + e);
}
}
}


输出 :

Exception : java.lang.NullPointerException

方案4 :

// Java code to demonstrate getFloat() method of Array class
import java.lang.reflect.Array;
public class GfG {
// main method
public static void main(String[] args)
{
// Declaring and defining a float variable
float a = 1 .0f;
try {
float x = Array.getFloat(a, 4 );
}
catch (Exception e) {
System.out.println( "Exception : " + e);
}
}
}


输出 :

Exception : java.lang.IllegalArgumentException: Argument is not an array

项目5 :

// Java code to demonstrate getFloat() method of Array class
import java.lang.reflect.Array;
public class GfG {
// main method
public static void main(String[] args)
{
// Declaring and defining a String array
String s[] = { "Geeks" , "for" , "Geeks" };
try {
float x = Array.getFloat(s, 4 );
}
catch (Exception e) {
System.out.println( "Exception : " + e);
}
}
}


输出 :

Exception : java.lang.IllegalArgumentException: Argument is not an array
© 版权声明
THE END
喜欢就支持一下吧
点赞14 分享