java - 从 Java 中的文件创建整数数组时,数组仅包含零?

标签 java arrays

所以这个程序需要能够接收一个包含一行文本和多行整数的文本文件,并将它们存储在单独的数组中。这是一个文本文件示例:

five hexing wizard bots jump quickly
21 5 6 11 15 9 10 3 34 22 28 5 15 2 3 4 21 5 3 18 27 5 20 9 6 23 19 20 7

我已经弄清楚如何将文本存储到字符数组中,并且已经弄清楚如何设置整数数组以接受文本文件中的整数。但是,每当我尝试打印该数组时,它都会填充零,而不是文本文件中包含的数字。这是到目前为止我的代码(将整数从文本文件复制到数组的代码位于程序的底部):

import java.util.*;
import java.io.*;

public class Decoder 
{
public static void main(String[] args) throws IOException
{
    Scanner keyboard = new Scanner(System.in);
    String fileName;

    System.out.println("Please enter the name of a file to be decoded: ");
    fileName = keyboard.nextLine();

    File testFile = new File(fileName);
    Scanner inputFile = new Scanner(testFile);

    String keyPhrase = inputFile.nextLine();

    char[] letterArray = new char[keyPhrase.length()];
    letterArray = keyPhrase.toCharArray();

    int counter = 0;
    while(inputFile.hasNextInt())
    {
        counter++;
        inputFile.nextInt();
    }

    int[] numArray = new int[counter];

    int i = 0;
    while(inputFile.hasNextInt())
    {
        numArray[i++] = inputFile.nextInt();
    }

    System.out.println(Arrays.toString(numArray));
}

答案可能非常简单(我对 Java 和编程都很陌生),但任何帮助将不胜感激!

最佳答案

您正在读取包含整数的行两次 - 第一次忽略它们。该 block 读取并忽略所有数字(以了解数组需要有多大):

int counter = 0;
while(inputFile.hasNextInt())
{
    counter++;
    inputFile.nextInt();
}

然后这个 block 尝试读取更多整数,但它们已经被读取了:

int i = 0;
while(inputFile.hasNextInt())
{
    numArray[i++] = inputFile.nextInt();
}

尝试使用 ArrayList 。当您向其中添加更多内容时,它们会动态增长:

ArrayList<Integer> numbers = new ArrayList<Integer>();
while(inputFile.hasNextInt())
{
    numbers.add(inputFile.nextInt());
}

然后您可以使用两个 toArray 之一方法(如果您特别需要数组)。另一种选择是扫描文件两次 - 一次获取数组的长度,然后再次实际加载数字。

关于java - 从 Java 中的文件创建整数数组时,数组仅包含零?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36415734/

相关文章:

c++ - 如何翻转数组的一部分?

java - JNI 将字符串从 C 传递到 java

java - mssql-jdbc-6.3.4.jre8-preview.jar 没有 sqljdbc_auth.dll

java - 怎样才能造出SQL语句

javascript - 即使使用 JavaScript 函数,AngularJs 也无法对数组进行排序

javascript - 卡在 else if 循环中

java - 在 n 个二维数组中搜索

java - System.setSecurityManager(null) 的影响

java - 如何摆脱错误: JSONArray[0] is not a JSONObject

javascript - 状态改变时如何更新组件