logo

Java'da sayaç değişkeni

Java'da bir sayaç değişkeni tekrarları saymak veya hangi tekrarda olduğumuzu bilmek için döngüde kullanılan özel bir değişken türüdür. Basit bir deyişle, sayaç değişkeni bir değişken Belirli bir kod parçasının kaç kez yürütüldüğünü takip eden sistem.

Sayaç değişkeni, normal değişkenlerin bildirildiği ve kullanıldığı şekilde bildirilir ve kullanılır. Sayaç değişkeni sadece tamsayı tipinde olabilir çünkü tamsayı tipi değişkenin değerini arttırmak çok kolaydır.

Sayaç değişkeninin anlaşılması ve kullanılması çok kolaydır. Sayaç değişkenini kullanma tekniği Java Şöyleki:

  1. Tekrarlanan döngüden önce onu sıfır veya bir olarak başlatmamız gerekir.
  2. Bundan sonra sayaç değişkenini ilgili döngü içerisinde bir arttırmalıyız.

Java'da sayaç değişkeni kavramını anlamak için basit bir örnek ele alalım.

CounterVariableExample1.java

 //create CounterVariableExample1 class to understand the concept of counter public class CounterVariableExample1{ //main() method start public static void main(String[] args) { //initialize counter int counter = 0; //using for loop to increment the counter variable for(int i=0; i<5; i++){ increment counter variable + 1; print the incremented value system.out.println(counter); } < pre> <br> <img src="//techcodeview.com/img/java-tutorial/50/counter-variable-java.webp" alt="Counter variable in Java"> <p>Let&apos;s take another example of a counter variable in which we will count the occurrence of the character in the string using counter variable.</p> <p> <strong>CounterVariableExample2.java</strong> </p> <pre> //create CounterVariableExample1 to count the occurence of each character in a string using counter variable class CounterVariableExample2 { //set maximum character size static final int MAX = 256; static void getNumberOfSameChar(String str) { // Create an array of size 256, i.e., ASCII_SIZE int count[] = new int[MAX]; //calculate the length of the string int len = str.length(); // Initialize count array index for (int i = 0; i <len; i++) count[str.charat(i)]++; create a character array of size len char chararray[]="new" char[len]; copying each string to chararray for (int i="0;" < len; i++){ chararray[i]="str.charAt(i);" initialize counter variable int j="0;" j++) { increment the if any match fount (str.charat(i)="=" chararray[j]) counter++; } (counter="=" 1) system.out.println( 'the occurrence '+str.charat(i) + ' is:' count[str.charat(i)]); main() method start public static void main(string[] args) type with default str="javaTpoint is the best learning website" ; call getnumberofsamechar() get occurence in getnumberofsamechar(str); pre> <p> <strong>Output</strong> </p> <img src="//techcodeview.com/img/java-tutorial/50/counter-variable-java-2.webp" alt="Counter variable in Java"> <hr></len;></pre></5;>