簡體   English   中英

如何在不使用hasNextInt()Java的情況下從文本文件讀取整數

[英]How to read integers from a text file without using hasNextInt() Java

因此,我是編程的新手,我們必須進行此實驗,在該實驗中,我們從只有一行數字的文本文件中讀取數據。 然后,我們必須將這些整數放入數組中。 我知道如何將數字放在單獨的行中而不是一行時讀取。 我也知道如何將數字放入數組中,因此不需要幫助。

我們允許使用的唯一方法是:

  • hasMoreTokens()
  • hasMoreLines()
  • readDouble()
  • readInt()
  • readLine()
  • readToken()

僅使用這些方法有沒有辦法做到這一點?

這是代碼:

import chn.util.FileInput;
import chn.util.FileOutput;

public class Compact {
    public Compact (FileInput inFile, FileOutput outFile){
        int[] compactArray = new int [21];
        int numZeroes = 0;
        int num;
        int length = compactArray.length;

    for (int i = 0; i < length; i++) { //making the array for the integers in the list
        compactArray[i] = 0;
    }

    while (inFile.hasMoreLines()) {
        num = 0;
        num = inFile.readInt(); //reads the integers per line
        compactArray[num]++;
    }

    for(int i = 0; i < length; i++) {
        if(compactArray[i] == 0) {
            length--;

            for(int j = i; j < length; j++) {
                compactArray[j] = compactArray[j+1];
            }
            i--; // Decrement i to check the value that was shifted
        } else { 
            numZeroes++;
        }
    }

    // now print the array without 0
    for(int i = 0; i < numZeroes; i++) {
        outFile.print(" " + compactArray[i]);
    }

    outFile.close();
}

由於某種原因,它只是返回一個零字符串。 我當時認為這可能與我閱讀代碼的方式有關。

輸入: numbers_line.txt ,其中只有一行: 1 8 3 43 4 56

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.Arrays;
import java.util.ArrayList;
import java.util.List; 

public class ReadIntFromFile {

     public static void main(String []args){
        String fileName = "numbers_line.txt";
        List<String> numbersArrayList = new ArrayList<String>();

        try (BufferedReader br = new BufferedReader(new FileReader(fileName))) {
            String line;
            while ((line = br.readLine()) != null) {
                numbersArrayList = Arrays.asList(line.split(" "));
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
        String[] numbersStringArray = new String[numbersArrayList.size()];
        numbersStringArray = numbersArrayList.toArray(numbersStringArray);
        int[] numbersIntArray = new int[numbersStringArray.length];
        for(int i = 0;i < numbersStringArray.length;i++) {
            numbersIntArray[i] = Integer.parseInt(numbersStringArray[i]);
        }

        for(int x : numbersIntArray)
             System.out.println(x);
     }
}

輸出:

1
8
3
43
4
56

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM