java - Count characters in specific line -
i reading file , check number of lines, characters , longest line , want know number of characters in second line of file. how can it?
    scanner input = new scanner(new filereader("c:/.../mrr569.fasta"));     int lines = 0;     int characters = 0;     int maxcharacters = 0;     string longestline = "";      while (input.hasnextline()) {         string line = input.nextline();         lines++;         characters += line.length();          if (maxcharacters < line.length()) {             maxcharacters = line.length();             longestline = line;         }      }     system.out.println(lines);     system.out.println(characters);     system.out.println(longestline);      
you need keep track of line on. create variable lineno.
int lineno=1;   you need store number of characters in second line:
int charsinsecondline=0;   and @ end of while loop increment variable:
lineno++;   then in while loop (before increment) add if statement checks if second line
if(lineno==2){     charsinsecondline=line.length(); }   so code becomes:
scanner input = new scanner(new filereader("c:/.../mrr569.fasta")); int lines = 0; int characters = 0; int maxcharacters = 0; int lineno = 1; int charsinsecondline = 0; string longestline = "";  while (input.hasnextline()) {     string line = input.nextline();     lines++;     characters += line.length();      if (maxcharacters < line.length()) {         maxcharacters = line.length();         longestline = line;     }      if(lineno==2){         charsinsecondline=line.length();     }     lineno++; } system.out.println(lines); system.out.println(characters); system.out.println(longestline); system.out.println(charsinsecondline);      
Comments
Post a Comment