gpt4 book ai didi

java - ArrayIndexOutOfBoundsException :0 occurs when trying to read in a file from the Linux command line in Java?

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:27:20 24 4
gpt4 key购买 nike

所以我试图从 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com