Anonymous Anonymous - 7 months ago 12
Java Question

How to count ";" in line

I want to count ";" in line from text file.

Ex. In my text file


  • case 1: int a; int b;

  • case 2: int c;

  • case 3: int x; int y; int z;



My expected out put is


  • line 1 have 2 ";" in line

  • line 2 have 1 ";" in line

  • line 3 have 3 ";" in line



My code

Scanner (input);

while(in.hasNext()){

String line = in.nextLine();
in.hasNextLine();
LOC++;
if (line.length() >0){
k = -1;

if(line.indexOf(";") != 1){
while(true){
k = line.indexOf(";");
if(k<0)break;
cCommand++;
}

}

}
}

System.out.println(output);


Thank you for your answering.

Answer

You can simply do:

int c=0;
for(char ch : line.toCharArray())
{
    if(ch==';') c++;
}