【发布时间】:2016-01-02 16:19:45
【问题描述】:
我在创建从命令行读取为参数的数组时遇到问题。该文件的第一行是一个整数 N,该文件的其余部分在每一行都包含字符串。第一个整数是数组的大小。我已经成功分配了数组,但是我无法让它读取 input.txt 文件的整行。
以下是 input.txt 文件的示例:
4
hey, 03982
bye, 30980324
no, 3290823
yes, 30948432
这是我的代码截图:
import java.util.Scanner;
import java.io.*;
import java.util.Arrays;
class databaseSearch{
public static void main( String[] args ){
Scanner sc = null;
// if no arguments are entered, print out
// error message and correct way to invoke program
if(args.length == 0){
errorMessage();
}
// Try and open the first argument on the command line
try{
sc = new Scanner(new File(args[0]));
}catch(FileNotFoundException e){
System.err.println(e.getMessage());
errorMessage();
}
int arraySize = sc.nextInt();
sc.nextLine();
String[] DB = new String[arraySize];
for( int i = 0; i < arraySize; i++ ){
DB[i] = sc.nextLine();
}
System.out.println(Arrays.toString(DB));
}
// errorMessage()
// prints out an error message with correct with to invoke program
// terminates after instructions are given
static void errorMessage(){
System.err.println("Please try again by running the program along with a correct file.");
System.exit(1);
}
}
【问题讨论】:
-
什么是业务变量?此示例无法验证,请尝试在调试器中运行它以逐步查看结果。什么是正确的?
-
修好了,应该是DB.length
标签: java arrays java.util.scanner stdin