2015-01-14 19 views
0

所以你我可以看到我從一個文件中讀取,並在文件顯示所有的整數和投入量在一個數組,我需要幫助僅僅是一個trycatch塊打印出「你沒有輸入任何內容」基本上,當命令行參數被用戶留空時。如何在命令行參數被用戶留空時正確顯示錯誤?

import java.util.Scanner; 
import java.io.File; 
import java.io.FileNotFoundException; 
import java.util.InputMismatchException; 

public class Print5{ 

    public static void main(String[] commandlineArgument) { 
     Integer[] array = Print5.readFileReturnIntegers(commandlineArgument[0]); 
     Print5.printArrayAndIntegerCount(array, commandlineArgument[0]); 
    } 

    public static Integer[] readFileReturnIntegers(String filename) { 

     Integer[] temp = new Integer[10000]; 
     int i = 0;  
     File file = new File(filename);//Connects File 
     Scanner inputFile = null; 

     try{ 
      inputFile = new Scanner(file); 
     } 
     catch(FileNotFoundException Exception1) { 
      System.out.println("File not found!"); //error message when mistyped 
     } 


     //where the blank error arg will go 
     if (inputFile != null) { 

      try { 
       while (inputFile.hasNext()) { 
        try { 
         temp[i] = inputFile.nextInt(); 
         i++; 
        } catch (InputMismatchException Exception3) { //change this back to e if doesnt work 
         inputFile.next(); 
        } 
       } 
      } 
      finally { 
       inputFile.close(); 
      } 

      Integer[] array = new Integer[i]; 
      System.arraycopy(temp, 0, array, 0, i); 
      return array; 
     } 
     return new Integer[] {}; 
    } 

    //Prints the array 
    public static void printArrayAndIntegerCount(Integer[] array, String filename) { 
     System.out.println("number of integers in file \"" + filename + "\" = " + array.length); 

     for (int i = 0; i < array.length; i++) { 
      System.out.println("index = " + i + "," + " element = " + array[i]); 
     } 
    } 
} 
+0

爲什麼你需要嘗試catch塊?你可以檢查它與如果條件在你的主要方法? – Sas

回答

1

顯示錯誤消息後添加覆在陣列的大小並退出該程序:

public static void main(String[] commandlineArgument) { 
    if(commandlineArgument.length < 1) { 
     System.err.println("Your error message"); // use the std error stream 
     System.exit(-1); 
    } 
    ... 

按照慣例,一個非零狀態參數System.exit()表示異常終止。

+0

啊。很簡單。非常感謝你。 – CMcorpse

0

只是檢查args數組長度:

public static void main(String[] commandlineArgument) { 

    if (commandlineArgument.length > 0) { 
     Integer[] array = Print5.readFileReturnIntegers(commandlineArgument[0]); 
     Print5.printArrayAndIntegerCount(array, commandlineArgument[0]); 
    } 
    else { 
      System.out.println("usage - ... your message"); 
    } 
    } 
相關問題