作者热门文章
- iOS/Objective-C 元类和类别
- objective-c - -1001 错误,当 NSURLSession 通过 httpproxy 和/etc/hosts
- java - 使用网络类获取 url 地址
- ios - 推送通知中不播放声音
所以我试图从 Linux 命令行接受一个文本文件到我的 Java 程序中,但是编译器给了我标题中提到的错误。它说错误发生在“String fileName = args[0];”这一行。有没有人碰巧知道为什么?这是我的代码:
public class Parsons_Decoder
{
// method: main
// purpose: receives key-phrase and sequence of integers and
// prints the secret message to the screen.
public static void main(String[] args) throws IOException
{
String fileName = args[0];
// reads incoming file (if it exists) and saves the key-phrase to
// String variable "keyPhrase"
File testFile = new File(fileName);
if(!testFile.exists())
{
System.out.println("\nThis file does not exist.\n");
System.exit(0);
}
Scanner inputFile = new Scanner(args[0]);
String keyPhrase = inputFile.nextLine();
// creates an ArrayList and stores the sequence of integers into it
ArrayList<Integer> numArray = new ArrayList<Integer>();
while(inputFile.hasNextInt())
{
numArray.add(inputFile.nextInt());
}
// decodes and prints the secret message to the screen
System.out.println();
System.out.print("Your secret message is: ");
for(int i = 0; i < numArray.size(); i++)
{
int num = numArray.get(i);
System.out.print(keyPhrase.charAt(num));
}
System.out.println("\n");
//keyboard.close();
inputFile.close();
}
}
最佳答案
更新:
你的教授要求你使用标准输入读入一个文件,使用如下命令:
java Diaz_Decoder < secretText1.txt
您的 main()
方法应该如下所示:
public static void main(String[] args) throws IOException {
// create a scanner using stdin
Scanner sc = new Scanner(System.in);
String keyPhrase = inputFile.nextLine();
// creates an ArrayList and stores the sequence of integers into it
ArrayList<Integer> numArray = new ArrayList<Integer>();
while (inputFile.hasNextInt()) {
numArray.add(inputFile.nextInt());
}
// decodes and prints the secret message to the screen
System.out.println();
System.out.print("Your secret message is: ");
for (int i = 0; i < numArray.size(); i++) {
int num = numArray.get(i);
System.out.print(keyPhrase.charAt(num));
}
System.out.println("\n");
}
关于java - ArrayIndexOutOfBoundsException :0 occurs when trying to read in a file from the Linux command line in Java?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36439461/
我是一名优秀的程序员,十分优秀!