Question:
Text file into array Java?
2014-03-04 08:22:43 UTC
So I'm having trouble with part of my assignment that requires reading a text file into three arrays. The information is:

E1 E2 E3
2497 12500 2
3323 13000 5
4521 18210 4
6789 8000 2
5476 6000 1
4423 16400 3
6587 25000 4
3221 10500 4
5555 15000 2
1085 19700 3
3097 20000 8
4480 23400 5
2065 19700 2
8901 13000 3


My current code so far:

import java.io.*;
import java.util.*;
public class Prog110
{
public static void main(String[] args)throws IOException
{
Scanner kbReader = new Scanner(new File("C:\\Users\\Guest\\Documents\\Java Programs\\Prog110\\Prog110.in"));

while(kbReader.hasNextLine())
{
String line = kbReader.nextLine();
String[] e1 = line.substring(0,4);
}
}
}

So I stopped there because it returned an incompatible types error, and now I'm unsure of what I can do to fix this, or if the way I'm storing the data into the arrays is correct. I was hoping that some could show me how I could properly store the data of E1, E2, and E3 into three separate arrays(each column is separated by a space). All help is greatly appreciated
Three answers:
?
2014-03-04 10:00:36 UTC
You can have a seperate array for the names.



This example should work for you:

http://javablogx.blogspot.com/2014/03/populating-three-different-arrays-from.html
?
2014-03-04 08:38:15 UTC
You should try reading it in and make sure your seperating the values by the space. so 2497_12500 that being the space but youll just do a normal space in your code. also if your doing a calculation you should be storing these values some where in which you need to assign some sort of array these values are assigned unless this is just rows of strings to look like numbers. E! should be an array in which you store the set of values which are seperated by a space so to store the next youd assign the next to E2 doing this in a linked list is alot easier. seperate them by lists and store based on the position and just read them from the scanner straight into your list. i hope this makes sense somewhat.
John
2014-03-05 02:01:08 UTC
import java.util.Scanner;

import java.io.*;



public class Program {

public static void main(String[] args) throws FileNotFoundException {

final int SIZE = 14;

int[] e1 = new int[SIZE];

int[] e2 = new int[SIZE];

int[] e3 = new int[SIZE];

String filePath = "C:\\Users\\Guest\\Documents\\Java Programs\\Prog110\\Prog110.in";



Scanner kbReader = new Scanner(new FileReader(filePath));

int idx = 0;

while (kbReader.hasNext()) {

e1[idx] = kbReader.nextInt();

e2[idx] = kbReader.nextInt();

e3[idx] = kbReader.nextInt();

idx++;

}

kbReader.close();



for (int i = 0; i < e1.length; i++) {

System.out.printf("%d %d %d%n", e1[i], e2[i], e3[i]);

}

}

}


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...