0

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);
        }
    }
}
3
  • 2
    @Berger No, args[0] is not null, it simply doesn't exist because size of array is 0 so there is no first element (indexed by 0). OP need to check for array length, not for null. Commented Mar 2, 2018 at 9:57
  • 1
    @Pshemo : Indeed , removed the incorrect comment . Commented Mar 2, 2018 at 9:58
  • @OP When there are no arguments provided then args array is simply empty like String[] 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 range 0..length-1, otherwise you will see exception about incorrect bounds. Commented Mar 2, 2018 at 10:04

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.