所以你我可以看到我從一個文件中讀取,並在文件顯示所有的整數和投入量在一個數組,我需要幫助僅僅是一個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]);
}
}
}
爲什麼你需要嘗試catch塊?你可以檢查它與如果條件在你的主要方法? – Sas