[英]How to read integers from a text file without using hasNextInt() Java
So I'm new to programming and we have to do this lab where we read from a text file that has only one line with numbers. 因此,我是编程的新手,我们必须进行此实验,在该实验中,我们从只有一行数字的文本文件中读取数据。 We then have to put those integers into an array. 然后,我们必须将这些整数放入数组中。 I know how to read the numbers when they are in separate lines but not when they are in one line. 我知道如何将数字放在单独的行中而不是一行时读取。 I also know how to put numbers into an array, so I don't need help with that. 我也知道如何将数字放入数组中,因此不需要帮助。
The only methods we are allowed to use are: 我们允许使用的唯一方法是:
hasMoreTokens()
hasMoreLines()
readDouble()
readInt()
readLine()
readToken()
Is there a way to do such while using only these methods? 仅使用这些方法有没有办法做到这一点?
Here is the code: 这是代码:
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();
}
For some reason it's simply returning a string of zeroes. 由于某种原因,它只是返回一个零字符串。 I was thinking it may have to do with the way I read the code. 我当时认为这可能与我阅读代码的方式有关。
Input: numbers_line.txt which has one line: 1 8 3 43 4 56 输入: 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);
}
}
Output: 输出:
1
8
3
43
4
56
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.