2015-08-16 87 views
0

阵列我有距离d文件:\ input.txt中 我想是我的代码,但我recevie ArrayIndexOutOfBoundException 为什么从用户那里得到这条道路与扫描仪类 这里?店字符串中使用扫描仪

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]); 
     } 
+1

你是怎么跑的? –

+0

@mahdieh你在哪一行得到ArrayIndexOutOfBoundException? –

回答

0

这会发生,如果args.length为0

你应该做

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

和其他不使用args[0]

计划将else块去,如果args.length == 0args[0] = filePath.next();会给ArrayIndexOutOfBoundException

+2

你看过第一行吗? –

+0

如果'args.length == 0'和'args [0] = filePath.next();''程序会进入其他地方'''会给出'ArrayIndexOutOfBoundException'。 –

+0

哎呀,我的坏,今天早上忘了拿我的咖啡:) –

1

你不能使用这里args[0] = filePath.next();阵列,因为你的数组没有初始化,给ArrayIndexOutOfBoundException,尝试:

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

+0

感谢所有的问题解决! – mahdieh

+0

@mahdieh如果答案提供了一些价值,请**向答案upvote **(如果在Web浏览器中查看,请单击向上的三角形)。如果某个答案解决了您的问题或解决了您的问题,**接受答案**(如果在浏览器中单击出现在向下三角形下方的大空白对号)。接受信号给您认为该问题关闭/解决的其他读者。 –

0

这很简单,如果

args.length == 0 

您无法访问

args[0] 

所以,你必须改变线路,

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

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