I'm pretty new to programming feel free to be harsh in your replies. Anything helps. Basically I'm trying to call in a method LineCount() but when I try to compile the command prompt complains about .class being expected at String[A] (line 8 I believe)
*Thank you guys for all your help! My code works now! I really appreciate all the input
import java.util.Scanner;
import java.io.*;
public class FileCount{
public static void main(String[] args) throws IOException{
String[] in = new Scanner(new File(args[0]));
System.out.println(lineCount(String[] in);
}
public static void lineCount(String[] A){
// check number of command line arguments
if(args.length != 1){
System.err.println("Usage: LineCount file");
System.exit(1);
}
// count lines, words, and chars in file
int lineCount = 0;
while( in.hasNextLine() ){
in.nextLine();
lineCount++;
}
in.close();
System.out.println( args[0]+" contains "+lineCount+" lines" );
}
}
-> There are many mistakes in your code, Besides other answers want to add that, Since you are passing lineCount(in)
as an argument to the linecount()
method , then refer to the parameter in lineCount(String[] A)
now via A
variable and not in
.
-> Also you cannot refer to args
inside linecount()
method since it is a parameter of main()
method and hence is limited to it in its scope.
-> You cannot do this String[] in = new Scanner(new File(args[0]));
, you are assigning a Scanner
instance to an String Array, you have to do it like this
Scanner in = new Scanner(new File(args[0]));
-> You are calling linecount()
inside a System.out.println()
method , although your method linecount()
has a return type of void, Dont put your method inside print()
function , because anyways it has got print()
statements inside it.
-> Maybe last , there could be more , Since your in
variable is of type Scanner
, change your method declaration to
public static void lineCount(Scanner in){
and now call it like lineCount(in)
from main()
.
Edit :- Since you are a beginner i will give you working code for your question:-
import java.util.Scanner;
import java.io.*;
public class FileCount{
public static void main(String[] args) throws IOException{
// check number of command line arguments, and check it in main()
if(args.length != 1){
System.err.println("Usage: LineCount file");
System.exit(1);
}
Scanner in = new Scanner(new File(args[0]));
System.out.println( args[0]+" contains "+lineCount(in)+" lines" ); //call this line in main() and not in linecount() as you refer to both args and need the linecount.
}
public static int lineCount(Scanner in){
// count lines, words, and chars in file
int lineCount = 0;
while( in.hasNextLine() ){
in.nextLine();
lineCount++;
}
in.close();
return lineCount; //return the linecount from method
}
}