java.nio.CharBuffer类的charAt()方法用于读取相对于当前位置的给定索引处的字符。
用法:
public final char charAt(int index)
参数:此方法获取要读取的字符相对于位置的索引;必须为非负且小于remaining()。
返回值:此方法返回索引position() +索引处的字符。
异常:如果索引的前提条件不成立,则此方法将引发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-
相关用法
- Java CharBuffer flip()用法及代码示例
- Java CharBuffer append()用法及代码示例
- Java CharBuffer limit()用法及代码示例
- Java CharBuffer rewind()用法及代码示例
- Java CharBuffer position()用法及代码示例
- Java CharBuffer subSequence()用法及代码示例
- Java CharBuffer reset()用法及代码示例
- Java CharBuffer read()用法及代码示例
- Java CharBuffer length()用法及代码示例
- Java CharBuffer order()用法及代码示例
- Java CharBuffer mark()用法及代码示例
- Java CharBuffer clear()用法及代码示例
- Java CharBuffer chars()用法及代码示例
- Java CharBuffer put()用法及代码示例
- Java CharBuffer get()用法及代码示例
注:本文由纯净天空筛选整理自RohitPrasad3大神的英文原创作品 CharBuffer charAt() methods in Java with Examples。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。