0

I have a file in path d:\input.txt I want get this path from user with Scanner class Here is my code but i recevie ArrayIndexOutOfBoundException Why?

if(args.length != 0)
        {
            readerWriter.readFile(args[0]);
        }
        else
        {
            System.out.println("Plese enter the path of your file");                
            Scanner filePath = new Scanner(System.in);
            args[0] = filePath.next();
            readerWriter.readFile(args[0]);
        }
2
  • 1
    how did you run this ? Commented Aug 16, 2015 at 7:18
  • @mahdieh at which line you get ArrayIndexOutOfBoundException ? Commented Aug 16, 2015 at 7:20

3 Answers 3

1

You can't using array here args[0] = filePath.next(); because your array is not initialized and give ArrayIndexOutOfBoundException, try:

String file = filePath.next(); readerWriter.readFile(file);

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

1 Comment

@mahdieh If an Answer provided some value, please give the Answer an upvote (click the upward triangle if viewing in a web browser). If an Answer solves your problem or resolves your Question, accept the Answer (click the big empty checkmark appearing below the downward triangle, if in a browser). Acceptance signals to other readers that you consider the Question closed/resolved.
0

It is simple, if

args.length == 0

you cannot access

args[0]

So you have to change the lines,

args[0] = filePath.next();
readerWriter.readFile(args[0]);

into

String myPath = filePath.next();
readerWriter.readFile(myPath);

Comments

0

This will happen if args.length is 0.

You should do

if(args.length != 0)
        {
            readerWriter.readFile(args[0]);
        }
        else
        {
            System.out.println("Plese enter the path of your file");                
            Scanner filePath = new Scanner(System.in);
            readerWriter.readFile(filePath.next());
        }

and not use args[0] in else.

Program will go in else block if args.length == 0 and args[0] = filePath.next(); will give ArrayIndexOutOfBoundException

3 Comments

have you looked at the first line?
Yes program will go in else if args.length == 0 and args[0] = filePath.next(); will give ArrayIndexOutOfBoundException .
oops, my bad, forgot to take my coffee this morning :)

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.