Java中的 CharBuffer charAt() 方法及示例
Java.nio.CharBuffer类的charAt()方法用于读取相对于当前位置的给定索引处的字符。
句法:
public final char charAt(int index)
参数:此方法采用要读取的字符的索引,相对于位置;必须是非负数且小于剩余()。
返回值:此方法返回索引位置()+索引处的字符。
异常:如果索引的先决条件不成立,此方法将抛出IndexOutOfBoundsException 。
下面是说明 charAt(int index) 方法的示例:
示例 1:
// Java program to demonstrate
// charAt() method
import java.nio.*;
import java.util.*;
public class GFG {
public static void main(String[] args)
{
// Creating the CharBuffer
try {
// creating object of CharBuffer
// and allocating size capacity
CharBuffer charbuffer
= CharBuffer.allocate(3);
// append the value in CharBuffer
// using append() method
charbuffer.append('a')
.append('b')
.append('c')
.rewind();
// print the CharBuffer
System.out.println("Original CharBuffer: "
+ Arrays.toString(
charbuffer.array()));
// Read char at particular Index
// using charAt() method
char value = charbuffer.charAt(2);
// Display the value
System.out.println("\nvalue at Index 0 is : "
+ value);
}
catch (IndexOutOfBoundsException e) {
System.out.println("\nindex is greater than"
+ " the capacity minus 1");
System.out.println("Exception throws : " + e);
}
}
}
输出:
Original CharBuffer: [a, b, c]
value at Index 0 is : c
示例 2:演示 IndexOutOfBoundsException。
// Java program to demonstrate
// charAt() method
import java.nio.*;
import java.util.*;
public class GFG {
public static void main(String[] args)
{
// Creating the CharBuffer
try {
// creating object of CharBuffer
// and allocating size capacity
CharBuffer charbuffer
= CharBuffer.allocate(3);
// append the value in CharBuffer
// using append() method
charbuffer.append('a')
.append('b')
.append('c')
.rewind();
// print the CharBuffer
System.out.println("Original CharBuffer: "
+ Arrays.toString(
charbuffer.array()));
// Read char at particular Index
// using charAt() method
char value = charbuffer.charAt(3);
// Display the value
System.out.println("\nvalue at Index 0 is : "
+ value);
}
catch (IndexOutOfBoundsException e) {
System.out.println("\nindex is greater than"
+ " the capacity minus 1");
System.out.println("Exception throws : " + e);
}
}
}
输出:
Original CharBuffer: [a, b, c]
index is greater than the capacity minus 1
Exception throws : java.lang.IndexOutOfBoundsException
参考: https://docs.oracle.com/javase/9/docs/api/ Java/nio/CharBuffer.html#charAt-int-