Reading text File and putting it in a array - java

I am trying to take a set of 25 numbers from a text file and convert it into a array. But I am lost.
I have read some other questions similar to this, but all of them used imports and extras, and I don't want to use any imports besides import java.io.*; nor any list.
Also the for loop within this is method is me just messing with it, because I couldn't figure it out.
public static int[] processFile (String filename) throws IOException, FileNotFoundException {
BufferedReader inputReader = new BufferedReader (new InputStreamReader(new FileInputStream(filename)));
String line;
int[] a = new int[25];
while (( line = inputReader.readLine()) != null){
int intValue = Integer.parseInt(line); //converts string into int
for (int i = 0; i < a.length; i++){
a[intValue]++;
}
}
return a;
}
public static void printArray (int[] a) {
for (int i = 0; i<a.length; i++) {
System.out.println (a[i]);
}
}
public static void main(String[] args) throws IOException, FileNotFoundException {
int [] array = processFile("C:\Users\griff_000\Desktop\TestWeek13.txt");
printArray(array);
}

I'm unclear about your whole import restriction, why exactly are you trying to limit the number of imports you have?
Anyway, looking at your code, it seems like the concept of arrays isn't all that clear with you.
Arrays are accessed under the syntax:
array[index] = value;
looking at your code, the line a[intValue]++; is actually finding the array index intValue (the number read from file) and incrementing it by one. Not only is this not what you want, numbers over the array length will cause an ArrayIndexOutOfBoundsException.
Making said amendments we get:
public static int[] processFile (String filename) throws IOException, FileNotFoundException{
BufferedReader inputReader = new BufferedReader (new InputStreamReader(new FileInputStream(filename)));
String line;
int[] a = new int[25];
int i = 0; // We need to maintain our own iterator when using a while loop
while((line = inputReader.readLine()) != null){
int intValue = Integer.parseInt(line); //converts string into int
a[i] = intValue; // Store intValue into the array at index i
i++; // Increment i
}
return a;
}
note the additional variable i being used in this context to facilitate the incrementing index number being used to access the array. If you examine this method carefully, a input file longer than 25 elements would also throw ArrayIndexOutOfBoundsException due to the variable i becoming 25 (beyond the limits of the array). To fix, I'd suggest changing the loop structure to a for-loop (assuming your input array is of fixed size) as follows:
public static int[] processFile (String filename) throws IOException, FileNotFoundException{
BufferedReader inputReader = new BufferedReader (new InputStreamReader(new FileInputStream(filename)));
String line;
int[] a = new int[25];
for(int i = 0; i < a.length; i++){
String line = inputReader.readLine(); // Move the readline code inside the loop
if(line == null){
// We hit EOF before we read 25 numbers, deal appropriately
}else{
a[i] = Integer.parseInt(line);
}
}
return a;
}
Note how the for loop integrates the iterator variable into one nice elegant line, keeping the rest of the code neat and readable.

Your mistake is in the line a[intValue]++;. You are telling Java to find the element at [intValue] and add 1 to it's current value. From your question, I understood that you want to put intValue as the array element.
Since you are using i as the iterator, to add the element simply use:
a[i] = intValue;

What you are doing here:
a[intValue]++;
is increasing the array position of the read value by one. If the number read is 2000 you are increasing a[2000]
you might want to do this
a[i]=intValue;

Related

Java scanner reading null from my text file?

I'm writing some code to read an input file of book titles, and putting the read lines into an array and trying to print out the array. But when I try to print out the array, it just returns 'null' for each read line. I'm not sure what I'm doing wrong or what my code is doing. Any suggestions? Thanks!
Code:
import java.io.*;
import java.util.*;
public class LibraryInputandOutputs {
public static void main(String args[]) throws IOException{
int lineCount = 0;
File inputFile = new File("bookTitles.inp.txt");
Scanner reader = new Scanner(inputFile);
while(reader.hasNextLine()) {
reader.nextLine();
lineCount++;
}
String[] bookArray = new String[lineCount];
while (reader.hasNextLine()) {
for (int i = 0; i < lineCount; i++) {
bookArray[i] = reader.next();
}
}
for (int k = 0; k < lineCount; k++) {
System.out.println(bookArray[k]);
}
reader.close();
inputFile.close();
}
}
My text file I'm reading from is 20 book titles, all on different lines.
My output on the terminal is 20 lines of null.
Lets break this down:
This reads every line of the input file, counts each one, and then discards them:
while(reader.hasNextLine()) {
reader.nextLine();
lineCount++;
}
You are now at the end of file.
Allocate a string array that is large enough.
String[] bookArray = new String[lineCount];
Attempt to read more lines. The loop will terminate immediately because reader.hasNextLine() will return false. You are already at the end of file.
So you the statement assigning to bookArray[i] won't be executed.
while (reader.hasNextLine()) {
for (int i = 0; i < lineCount; i++) {
bookArray[i] = reader.next();
}
}
Since bookArray[i] = ... was never executed above, all of the array elements will still be null.
for (int k = 0; k < lineCount; k++) {
System.out.println(bookArray[k]);
}
One solution is to open and read the file twice.
Another solution is to "reset" the file back to the beginning. (A bit complicated.)
Another solution would be to use a List rather than an array so that you don't need to read the file twice.
Another solution is to search the javadocs for a method that will read all lines of a file / stream as an array of strings.
(Some of these may be precluded by the requirements of your exercise. You work it out ... )
The nested loop in step 3 is also wrong. You don't need a for loop inside a while loop. You need a single loop that "iterates" the over the lines and also increments the array index (i). They don't both need to be done by the loop statement itself. You could do one or the other (or both) in the loop body.
Stephen C has already pointed out the main problems with your logic. You're trying to loop twice through the file but you've already reached the end of the file the first time. Don't loop twice. "Merge" both the while loops into one, remove that for loop inside the while loop and collect all the book titles. You can then use the size of the list to print them later on. My Java might be rusty but here it goes -
import java.io.*;
import java.util.*;
public class LibraryInputandOutputs {
public static void main(String args[]) throws IOException {
// int lineCount = 0; - You don't need this.
File inputFile = new File("bookTitles.inp.txt");
Scanner reader = new Scanner(inputFile);
// Use an array list to collect book titles.
List<String> bookArray = new ArrayList<>();
// Loop through the file and add titles to the array list.
while(reader.hasNextLine()) {
bookArray.add(reader.nextLine());
// lineCount++; - not needed
}
// Not needed -
// while (reader.hasNextLine()) {
// for (int i = 0; i < lineCount; i++) {
// bookArray[i] = reader.next();
// }
// }
// Use the size method of the array list class to get the length of the list
// and use it for looping.
for (int k = 0; k < bookArray.size(); k++) {
System.out.println(bookArray[k]);
}
reader.close();
inputFile.close();
}
}
I agree with Stephen C. In particular, using a List is usually better than an array because it's more flexible. If you need an array, you can always use toArray() after the List is filled.
Are your book titles on separate lines? If so you might not need a Scanner class, and could use something like a BufferedReader or LineNumberReader.

I read my text file, now how do I store the values into a 2D array?

As mentioned, I already managed to read in the file, I'm looking for a method to added to a 2D array. This is what I read:
20 10 8
4.5 8.45 12.2
8.0 2.5 4.0
1.0 15.0 18.0
3.5 3.5 3.5
6.0 5.0 10.0
import java.io.*;
import java.util.*;
public class Packages
{
public static void main(String[] args)throws IOException,FileNotFoundException
{
BufferedReader reader = new BufferedReader(new FileReader("Dimensions.txt"));
while (true)
{
String line = reader.readLine();
if(line==null);
{
break;
}
System.out.println(line);
}
reader.close();
}
}
The following solution uses a 2D array to store the numbers from your file. This would be an appropriate solution if the structure of your input is both known and well-defined. By this I mean that every row has three numbers, and you also know how many rows there are. If not, then you might want to use a Java collection class instead here.
public static void main(String[] args) throws IOException, FileNotFoundException {
// change this value to whatever row count you actually have
int NUM_ROWS = 100;
double[][] array = new double[NUM_ROWS][3];
BufferedReader reader = new BufferedReader(new FileReader("Dimensions.txt"));
int counter = 0;
while (true) {
String line = reader.readLine();
if (line == null) break;
String[] parts = line.trim().split("\\s+");
for (int i=0; i < 3; ++i) {
array[counter][i] = Double.parseDouble(parts[i]);
}
System.out.println(line);
++counter;
}
reader.close();
}
Create a scanner to read the line, Scanner scanner = new Scanner(line).
Create a loop that reads next item, scanner.next() or scanner.nextDouble() while it has next.
Put each into array at its given spot by maintaining a count for lineNumber and doubleCount. If you do not know the dimension size you will have to do a loop that counts each line and another that counts how many doubles in the line.

Multiple integer read in java with bufferedreader in java

I working on a program where I have to read about 10^6 integers.
I tried working with the scanner class however when i tried for 800000*3 inputs, it took around 12.38 seconds.
I also tried tried to work with the BufferedReader which actually worked faster but then it does not take the input i give as desired.
For e.g. if I want to read 3 numbers separated with a space, three consecutive nextInt() would work, but such is not the case for BufferedReader, it accepts the space as a string and while parsing the string into integer throws NumberFormatException exception.
input e.g. "8347 394730 3487", all three numbers must be stored separately.
code e.g
public static void main(String[] args) throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String b=br.readLine();
int x=Integer.parseInt(b);
b=br.readLine();
int x1=Integer.parseInt(b);
b=br.readLine();
int x2=Integer.parseInt(b);
System.out.println(x+x1+x2);
}
Also the numbers can be as large as 10^10.
So I need help in using BufferedReader for such input. Also if at all there is any other alternate but faster method for reading integers, will be good enough.
Thank you
get the String and then use this :
String[] numberList = yourString.split("\\s+");
List<Integer> myList = new ArrayList<Integer>();
for(String num : numberList){
myList.add(Integer.parseInt(num));
}
update* : please try this one
public class Answer {
public static void main(String[] args) throws Exception {
List<String> eachLineList = new ArrayList<String>();
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String b = br.readLine();
eachLineList.add(b.trim()); //Line 1 added to String list
b = br.readLine();
eachLineList.add(b.trim()); //Line 2 added to String list
b = br.readLine();
eachLineList.add(b.trim()); //List 3 added to String list
String[] numbers;
for (String line : eachLineList) {
numbers = line.split("\\s+");
if (numbers.length <= 1) {
//means if there was one or less integer each line don't do anything
break;
} else {
int intNum;
int temp = 0;
for (String num : numbers) {
intNum = Integer.parseInt(num);
temp += intNum;
}
System.out.println(temp);
}
}
}}
if you enter something like this "8347 394730 3487" in each line the sum will be return back to you ~
You may want to try receiving it as a String.
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String b=br.readLine();
String[] token = b.split(" "); //Split into String array by space
int[] num = new int[token.length]; //Create int array
for(int x=0; x<token.length; x++)
num[x] = Integer.parseInt(token[x]); //Store all string array into int array
for(int x=0; x<num.length; x++) //Printing
System.out.print(num[x] + " ");
Given your input in one line with spaces, the output is as follows:
Output:8347 394730 3487
YOu can check below code once.
public static void main(String[] args) throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String []b=br.readLine().split(" ");
for(int i=0;i<b.length;i++)
{
System.out.print(Integer.parseInt(b[i]));
}
}
I managed to get the answer somehow, with a little help from stackoverflow ofcourse
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String b=br.readLine();
String[] numbers=b.split(" ");
long[] x=new long[numbers.length];
for(int i=0;i<numbers.length;i++)
{
x[i]=Long.parseLong(numbers[i]);
System.out.println(x[i]);
}
The String.split(separator) method can be used to split a string into an array of strings, with the separator regex providing the separator. Refer to the String and Pattern javadoc for the complete description.
However, if you are really concerned about performance, you could potentially reduce the time even further by using String.indexOf and String.substring to extract the numbers for parsing. Or potentially parse them yourself to avoid the overhead of creating strings.

Importing text file and doubling array

I'm trying to write a method that imports a text file of a very large quantity of words, and then find words of a certain length and print them out.
I'm not looking for code, but rather a clarification if I'm correctly understanding what I'm trying to accomplish.
So, I'm going to import the text using throw exception, and take the number of letters of a specific word:
public static void name(int size) throws Exception{
Scanner inputFile = new Scanner(new File("2of12inf.txt"));
And then create a new array list:
int[] list = new int[MAX_SIZE]; //MAX_SIZE is initially a small number, say 100
int listSize = 0;
Where if the size of the list of words exceeds my MAX_SIZE array, then I'm going to copy the existing array and double it, in order to have the numbers of words fit in the list.
if (listSize == list.length)
{
int[] temp = new int [2*list.length];
for(int i = 0; i < list.length; i++){
temp[i] = list[i];}
list = temp;
}
list[listSize] = size;
listSize++;
inputFile.close();}
This is my raw understanding of how I'm suppose to write the method, is this the correct thinking of just being able to read in words and give a list of them?
EDIT: Sorry, I didn't mention that I'm not to use ArrayLists.
If you know which length you are interested in when before you run the program is suffices to just save those words while you iterate through the words.
Like this I mean:
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.SortedSet;
import java.util.TreeSet;
public class WordLengthPrinter {
public static void main(String[] args) throws Exception {
if (args.length != 2)
throw new IllegalArgumentException("Specify filename as first parameter. Word length is second.");
final String fileName = args[0]; // file name is first input argument
final int wordLength = Integer.parseInt(args[1]); // the desired wordlength is second argument
// lets store the words of correct size in a sorted set
SortedSet<String> wordsOfDesiredLength = new TreeSet<String>();
// read file line by line while checking word lengths and only store words of correct length
try (BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(fileName)))) {
String line = null;
while ( (line = reader.readLine()) != null) {
if (line.length() == wordLength) wordsOfDesiredLength.add(line);
}
}
// print resulting words
for (String word : wordsOfDesiredLength) {
System.out.println(word);
}
}
}

Counting numbers in a text file using Java

This has been troubling me for a while now. I normally don't tend to ask help and do my research, but I couldn't find an answer.
How do I write a program that reads a text file, and calculate how many times a certain number shows up?
I'm a huge beginner in Java, and also programming in general.
Here's my code.
This code generates a text file that has 100 random numbers
import java.io.*;
public class Rolling
{
public static void main (String[] args) throws IOException
{
int randomNum;
PrintWriter fileout = new PrintWriter (new FileWriter ("randumnums.txt"));
for (int i= 0; i < 101; i++)
{
randomNum = (int) (Math.random() * 100);
fileout.println (randomNum);
}
fileout.close();
}
}
Now the trouble I'm having is that I need to read the file and write a code saying X number was rolled 3 times. e.g the number 4 appeared 5 times in the text file, so I would need it to print "the number 4 was rolled 5 times".
import java.io.*;
public class Reading
{
public static void main (String[] args) throws IOException
{
BufferedReader readFile = new BufferedReader (new FileReader ("randumnums.txt"));
int number = 0;
int inMarks [] = new int [100];
for (int i = 0; i < 100; i++)
{
inMarks [i] = Integer.parseInt(readFile.readLine());
}
}
}
You're actually pretty close. It's clear that you're going to have to keep track of your counts in some kind of list, and an array will do quite nicely here.
First, after instantiating inMarks, initialize every value in it to 0:
int inMarks [] = new int [100];
for (int i = 0; i < 100; i++)
{
inMarks [i] = 0;
}
Then change the loop below to this:
String nextLine = null;
while ((nextLine = readFile.readLine()) != null)
{
int thisInt = Integer.parseInt(nextLine);
inMarks[thisInt] = inMarks[thisInt] + 1;
}
inMarks now perfectly tracks how many times each distinct int was rolled in the file. I'm going to let you implement the print-out part of the assignment, since that will give you a better understanding of how this solution works.
I have the feeling you are looking for something like this (I haven't tested this code)
import java.io.*;
public class Reading {
public static void main (String[] args) throws IOException {
BufferedReader readFile = new BufferedReader (new FileReader("randumnums.txt"));
int number = 0;
int inMarks [] = new int [100];
String readNumber = "";
while ((readNumber = readFile.readline()) != null) {
number = Integer.parseInt(readNumber);
inMarks[number]++;
}
}
}
The code above basically has an array of 100 integers. We then start reading the file until nothing can be read anymore. Everytime we read a line, we parse into an integer (which normally you should wrap around a try...catch). We then increase by 1 the number of times we have read this number by increasing the corresponding index in the array. So if you want to know how many times the number '32' appeared, you would do System.print.out(inMarks[32]);

Categories

Resources