I wanted to write wc program in java so wrote this code It works well when I write the command in cmd but when I don't write anything for args it should be work for all of them but it wouldn't work and give me an Exception with args[0].equal ... . Thank you for your helps!
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int linesNumber = 0;
int wordsNumber = 0;
int charsNumber = 0;
String line;
String word;
while (!(line = scan.nextLine()).isEmpty()) {
linesNumber++;
Scanner reader = new Scanner(line); //reading lines
while (reader.hasNext()) {
word = reader.next();
wordsNumber++;
charsNumber += word.length();
}
}
if(args[0].isEmpty()){
System.out.print(linesNumber +" " +wordsNumber +" " +charsNumber);
}else if(args[0].equals("-l") || args[0].equals("--lines")){
System.out.println(linesNumber);
}else if(args[0].equals("-w") || args[0].equals("--words")){
System.out.println(wordsNumber);
}else if(args[0].equals("-c") || args[0].equals("--chars")){
System.out.println(charsNumber);
}
}
}
args[0]is notnull, it simply doesn't exist because size of array is0so there is no first element (indexed by 0). OP need to check for array length, not fornull.argsarray is simply empty likeString[] args = {};so there are no elements in there, not even first one (indexed as 0). Before trying to access element at specified index (like[0]), you need to make sure that such element exist. Valid indexes are in range0..length-1, otherwise you will see exception about incorrect bounds.