logo

Tellervariabel i Java

En tellervariabel i Java er en spesiell type variabel som brukes i loopen for å telle repetisjonene eller for å vite om hvilken repetisjon vi befinner oss i. Med enkle ord er en motvariabel en variabel som holder styr på antall ganger en bestemt kodebit blir utført.

Tellervariabelen deklareres og brukes på samme måte som de normale variablene deklareres og brukes. Tellervariabelen kan være av bare heltallstype fordi det er veldig enkelt å øke verdien av heltallstypevariabelen.

Tellervariabelen er veldig enkel å forstå og bruke. Teknikken for å bruke tellervariabelen i Java er som følgende:

  1. Før den gjentatte syklusen må vi initialisere den til null eller én.
  2. Etter det må vi øke tellervariabelen i en innenfor den respektive syklusen.

La oss ta et enkelt eksempel for å forstå konseptet med tellervariabelen i Java.

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;>