Search code examples
javaargs

Why is not working with no args input in java


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);
        }
    }
}

Solution

  • I believe that where you have

    if(args[0].isEmpty())
    

    you mean

    if (args.length==0)
    

    If you pass no arguments to the program, args will be an empty array, so trying to access args[0] at all will raise an exception.