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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。