مشخصات مقاله
-
1604
-
0.0
-
5841
-
0
-
0
آموزش Java – کار با تابع ()charAt در Java
آموزش Java – کار با تابع charAt()
متد String charAt() مقدار char یا کاراکتر مورد نظر موجود در اندیس (شماره ی مکان قرار گیری) ورودی را برمی گرداند. اندیس از 0 آغاز می شود. اگر شماره ی اندیس از بازه ی اندیس و طول رشته ی ورودی بزرگتر باشد یا مقدار آن منفی باشد، خطای StringIndexOutOfBoundsException را بجای خروجی برمی گرداند.
Signature متد (اسم و پارامترهای ورودی متد)
signature متد نام برده به شرح زیر می باشد:
public char charAt(int index)
پارامتر ورودی
index: شماره ی مکان قرارگیری کاراکتر را مشخص می کند. اندیس در جاوا از 0 آغاز می شود.
خروجی
char value
interface میزبان متد
CharSequence interface
صدور خطا
StringIndexOutOfBoundsException : اگر اندیس یک مقدار منفی باشد یا از بازه ی اندیس و طول رشته ی مورد نظر بزرگتر باشد، این خطا رخ می دهد.
مثال کاربردی از متد Java String charAt()
public class CharAtExample{
public static void main(String args[]){
String name="javatpoint";
char ch=name.charAt(4);//returns the char value at the 4th index
System.out.println(ch);
}}
خروجی:
t
StringIndexOutOfBoundsException with charAt()
در مثال زیر مقدار اندیسی که به متد فرستاده می شود، از طول رشته و بازه ی اندیس رشته ی مورد نظر بزرگتر است. همان طور که انتظار می رود، خطای StringIndexOutOfBoundsException در زمان اجرا صادر می شود.
public class CharAtExample{
public static void main(String args[]){
String name="javatpoint";
char ch=name.charAt(10);//returns the char value at the 10th index
System.out.println(ch);
}}
خروجی:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 10 at java.lang.String.charAt(String.java:658) at CharAtExample.main(CharAtExample.java:4)