I have a Parser class which takes in a List of strings, and prints them out line by line. I want the method linecount() (which does not take in any parameter) to output the number of lines in total i.e.:

import java.util.*;

public class Parser{
  private static List<String> lines;

  public static String parse(List<String> lines){
    return String.join(System.lineSeparator(), lines); 
  }

  public static int linecount(){
    String newString = String.join(System.lineSeparator(), lines); 
    return (newString.split("[\r\n]")).length;
  }
}

Such that when the List of string is given as: List lines = Arrays.asList(new String[]{"one", "two three", ""}), calling Parser.parse(lines) will give you

one
two three

and thus, Parser.parse(lines).linecount() should output 3. However, I came across the error The method linecount() is undefined for the type java.lang.String. Why is this so?

2 Answers

-1
Tanmay_vijay On
import java.util.*;

public class Parser{
  private List<String> lines;

  public String parse(List<String> lines){
    this.lines = lines;
    return String.join(System.lineSeparator(), lines); 
  }

  public int linecount(){
    String newString = String.join(System.lineSeparator(), lines); 
    return (newString.split("[\r\n]")).length;
  }
}

main()

Parser p = new Parse();
List lines = p.parse(Arrays.asList(new String[]{"one", "two three", ""}));
System.out.println(lines);

System.out.println(p.linecount());
0
Khalid Shah On
Parser.parse(lines).linecount();//<--------- Here is the problem

Parser.parse() return a String and linecount() is the static function of Parser class. Its not the function of String class. you cannot call in that way Parser.parse(lines).linecount() and thats why it gives a error linecount() is undefined for the type java.lang.String. you have to call separately.

Parser.parse(lines);
Parser.linecount();

And you have to popultae List<String> lines Object before calling linecount().

Your Regex is not Right also. Replace "[\r\n]" with "[\\r | \\n]" . Output of program is stated at the end.

import java.util.Arrays;
import java.util.List;

public class Parser {

  private static List<String> lines;

  public static String parse(List<String> lines) {
    return String.join(System.lineSeparator(), lines);
  }

  public static int linecount() {
    String newString = String.join(System.lineSeparator(), lines);
    return (newString.split("[\\r | \\n]")).length;
  }

  public static void main(String[] args) {
    lines = Arrays.asList("one", "two three", "");
    lines.forEach(System.out::println);
    int count = Parser.linecount();
    System.out.println(count);
  }
}

Output :

one
two three

3