Read int from file separated by comma - java

I have this code here, that reads numbers from a file and stores them in a String array.
public static void main(String [] args) throws Exception{
BufferedReader br = new BufferedReader(new FileReader("/Users/Tda/desktop/ReadFiles/scores.txt"));
String line = null;
while((line = br.readLine()) != null){
String[] values = line.split(",");
for(String str : values){
System.out.println(str);
}
}
System.out.println("");
br.close();
}
But if I wanted to store the values from the String array in a int array, how should I do?
The file that I'm reading looks something like this.
23,64,73,26
75,34,21,43

After String[] values = line.split(",");...
// new int[] with "values"'s length
int[] intValues = new int[values.length];
// looping over String values
for (int i = 0; i < values.length; i++) {
// trying to parse String value as int
try {
// worked, assigning to respective int[] array position
intValues[i] = Integer.parseInt(values[i]);
}
// didn't work, moving over next String value
// at that position int will have default value 0
catch (NumberFormatException nfe) {
continue;
}
}
... and to test:
System.out.println(Arrays.toString(intValues));

Use parseInt(String) to convert every string to int
http://docs.oracle.com/javase/7/docs/api/java/lang/Integer.html#parseInt%28java.lang.String%29
int[] intvalues = new int[values.length];
for (int i = 0; i < values.length; i++) {
intvalues[i] = Integer.parseInt(values[i]);
}

You would need to parse your string into an int:
while((line = br.readLine()) != null){
String[] values = line.split(",");
int[] values2=new int[values.length];
for(int i=0; i<values.length; i++){
try {
values2[i]= Integer.parseInt(values[i]);
//in case it's not an int, you need to try catching a potential exception
}catch (NumberFormatException e) {
continue;
}
}
}

Related

incompatible types: String[] cannot be converted to String

I'm being completely beaten up by types in Java.
I have coordinates in a txt file, which ultimately I want to format into an array of these co-ordinates, with each array item being a double.
Each line of my txt file looks like so:
13.716 , 6.576600074768066
Currently, I'm trying to split this line into an array of two Strings, which I will then try and parse into doubles, but I keep getting the error in the title. Where am I going wrong?
Any other better approaches on converting my Arraylist of Strings to a formatted list of double coordinates would be great, like so
[[0,1], [0,2], 0,4]
Code:
public static String[] getFileContents(String path) throws FileNotFoundException, IOException
{
InputStream in = new FileInputStream(new File(path));
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
List<String> data = new ArrayList<String>();
StringBuilder out = new StringBuilder();
String line;
// Skips 1376 characters before accessing data
reader.skip(1378);
while ((line = reader.readLine()) != null) {
data.add(line);
// System.out.println(line);
}
for (int i=0; i < data.size(); i++){
data.set(i, data.get(i).split(","));
}
// String[] dataArr = data.toArray(new String[data.size()]);
// Test that dataArr[0] is correct
// System.out.println(data.size());
// List<String> formattedData = new ArrayList<String>();
// for (int i = 0; i < data.size(); i++){
// formattedData.add(dataArr[i].split(","));
// }
reader.close();
return dataArr;
}
The split(",") method return array of string string[] and you can't set string by array of string.
Crate point class with let lan double variabels and then create array of this point and them fill them with data from reading each line:
class Point{
double lat;
double len;
Point(double lat, double len){
this.lat = lat;
this.len = len;
}
}
And then use this class in your code:
public static String[] getFileContents(String path) throws FileNotFoundException, IOException
{
InputStream in = new FileInputStream(new File(path));
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
List<String> data = new ArrayList<String>();
StringBuilder out = new StringBuilder();
String line;
// Skips 1376 characters before accessing data
reader.skip(1378);
while ((line = reader.readLine()) != null) {
data.add(line);
// System.out.println(line);
}
List<Point> points = new ArrayList<Point>();
for (int i=0; i < data.size(); i++){
double lat = Double.parseDouble(data.get(i).split(",")[0]);
double len = Double.parseDouble(data.get(i).split(",")[1]);
points.add(new Point(lat, len));
//data.set(i, data.get(i).split(","));
}
// String[] dataArr = data.toArray(new String[data.size()]);
// Test that dataArr[0] is correct
// System.out.println(data.size());
// List<String> formattedData = new ArrayList<String>();
// for (int i = 0; i < data.size(); i++){
// formattedData.add(dataArr[i].split(","));
// }
reader.close();
return dataArr;
}
you can update your while loop like this
while ((line = reader.readLine()) != null) {
String[] splits = line.split(",");
for(String s : splits) {
data.add(s);
}
}

Parsing text file to jagged array

I have the following file
3
2,3,4,5
6,7,8
9,10
and I am trying to convert it to pass it as jagged array of double. By that I mean, I am trying to store this as
double[][] myArray = {{2,3,4},{6,7},{9}}
double[] secondArray = {5,8,10}
I have been able to get the values read from the file but I am stuck on 2 things.
How can I convert the values into double array?
How can I store the last elements into a new array?
I am facing the error because my array contains comma separated values but how can I get the individual values to convert to double? I am still new to Java so I am not aware of all the inbuilt methods.
here is what I have so far
public double[] fileParser(String filename) {
File textFile = new File(filename);
String firstLine = null;
String secondLine = null;
String[] secondLineTokens = null;
FileInputStream fstream = null;
try {
fstream = new FileInputStream(filename);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
try {
firstLine = br.readLine(); // reads the first line
List<String> myList = new ArrayList<String>();
while((secondLine = br.readLine()) != null){
myList.add(secondLine);
//secondLineTokens = secondLine.split(",");
}
String[] linesArray = myList.toArray(new String[myList.size()]);
for(int i = 0; i<linesArray.length; i++){
System.out.println("tokens are: " + linesArray[i]);
}
double[] arrDouble = new double[linesArray.length];
for(int i=0; i<linesArray.length; i++)
{
arrDouble[i] = Double.parseDouble(linesArray[i]); #error here
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
It looks like the first line gives you the number of lines in the rest of the file. You can leverage it to make the arrays upfront, like this:
int n = Integer.parseInt(br.readLine());
double a[][] = new double[n][];
double b[] = new double[n];
for (int i = 0 ; i != n ; i++) {
String[] tok = br.readLine().split(",");
a[i] = new double[tok.length-1];
for (int j = 0 ; j != a[i].length ; j++) {
a[i][j] = Double.parseDouble(tok[j]);
}
b[i] = Double.parseDouble(tok[tok.length-1]);
}
Similarly, you can use String.split method to find out how many entries is to be added to the jagged array. This way the code becomes much shorter, because you can pre-allocate all your arrays.
Demo.

How to get int array from string array

File myFile = new File(
Environment.getExternalStorageDirectory().getAbsolutePath(),
"Notes/test.txt"
);
BufferedReader br = new BufferedReader(new FileReader(myFile));
String line = br.readLine();
while ((line = br.readLine()) != null) {
b = line.split(",");
xpoints = new int[b[0].length()];
ypoints = new int[b[1].length()];
for (int i = 1; i < b[0].length(); i++) {
xpoints[i] = Integer.parseInt(b[0]);
ypoints[i] = Integer.parseInt(b[1]);
}
/*direction(xpoints, ypoints);*/
}
br.close();
Here, I get X and Y value from b[0] and b[1]. I want to store this values in integer array(like int []x and int []y).How can i get all these values in array as i said earlier?
You should parse your String into int like:
x[i] = Integer.parseInt(str);
for every single String representation of each int element
beware to provide into str though only integer because it will throw NumberFormatException otherwise.
You can iterate over the String array in a loop and then store the values in an int array of the same size.
int[] intArray = new int[b.length];
for(int i = 0; i < b.length; i++){
try{
intArray[i] = Integer.parseInt(b[i]);
catch(NumberFormatException e){
//handle exception
}
}
In your while statement when you do a split do this:
String[] b = line.split(splitsby);
int[] intArray = new int[b.length];
for (int stringIndex = 0; stringIndex < b.length; stringIndex++) {
intArray[stringIndex] = Integer.parseInt(b[stringIndex]);
}
System.out.println("X = " + intArray[0] + " Y = " + intArray[1]);
This is assuming that every value in b can be parsed as an Integer
Since you dont know the exact size of the elements you will get from file, I suggest you to create a ArrayList.
Arralist<Integer> a=new ArrayList<Integer>();
Arralist<Integer> b=new ArrayList<Integer>();
Then
File myFile = new File(Environment
.getExternalStorageDirectory().getAbsolutePath(),
"Notes/test.txt");
BufferedReader br = new BufferedReader(new FileReader(myFile));
String line=br.readLine();
String splitsby = ",";
while ((line = br.readLine()) !=null) {
String[] b=line.split(splitsby);
System.out.println("X = "+b[0]+" Y = "+b[1]);
a.add(Integer.parseInt(b[0]);
b.add(Integer.parseInt(b[1]);
}
br.close();
You can add this method:
private ArrayList<Integer> getIntegerArray(ArrayList<String> stringArray) {
ArrayList<Integer> result = new ArrayList<Integer>();
for(String stringValue : stringArray) {
try {
// convert String to Integer and store it into integer array list
result.add(Integer.parseInt(stringValue));
} catch (NumberFormatException nfe) {
// System.out.println("Could not parse " + nfe);
Log.w("NumberFormat", "Parsing failed! " + stringValue + " can not be an integer");
}
}
return result;
}
You can use Integer.parseInt() method to convert string into integer. you have to go through each string array element to use above method. Following like code can be used in any place as per your requirement.
int[] x = new int[2];
x[0] = Integer.parseInt(b[0]);
x[1] = Integer.parseInt(b[1]);
Integer.parseInt(b[0]);
See the Javadoc for more information.

Txt file into a double 2d array

I am trying to read a txt file into a array of doubles. I am using the following code which reads every line of the file:
String fileName="myFile.txt";
try{
//Create object of FileReader
FileReader inputFile = new FileReader(fileName);
//Instantiate the BufferedReader Class
BufferedReader bufferReader = new BufferedReader(inputFile);
//Variable to hold the one line data
String line;
// Read file line by line and print on the console
while ((line = bufferReader.readLine()) != null) {
System.out.println(line);
}
//Close the buffer reader
bufferReader.close();
}catch(Exception e){
System.out.println("Error while reading file line by line:"
+ e.getMessage());
}
However I want to store the txt file into a 2d double array.
I ve tried the above to load also the dimension of the txt. But I am having problems with the exceptions catch (NoSuchElementException e), it seems that it couldnt read the file.
try {
while (input.hasNext()) {
count++;
if (count == 1) {
row = input.nextInt();
r = row;
System.out.println(row);
continue;
} else if (count == 2) {
col = input.nextInt();
System.out.println(col);
c = col;
continue;
} else {
output_matrix = new double[row][col];
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
String el = input.next();
Double temp = Double.valueOf(el);
double number = temp.doubleValue();
//output_matrix[i][j] = el;
output_matrix[i][j] = number;
//System.out.print(output_matrix[i][j]+" ");
}
//System.out.println();
}
}
}
} catch (NoSuchElementException e) {
System.err.println("Sfalma kata ti tropopoisisi toy arxeioy");
System.err.println(e.getMessage()); //emfanisi tou minimatos sfalmatos
input.close();
System.exit(0);
} catch (IllegalStateException e) {
System.err.println("Sfalma kata ti anagnosi toy arxeioy");
System.exit(0);
}
You might want to be using the Scanner class for it, especially the Scanner.nextDouble() method.
Also, if you don't know in advance the dimensions of the array - I'd suggest using an ArrayList instead of a regular array.
Code example:
ArrayList<ArrayList<Double>> list = new ArrayList<>();
while ((line = bufferReader.readLine()) != null) {
ArrayList<Double> curr = new ArrayList<>();
Scanner sc = new Scanner(line);
while (sc.hasNextDouble()) {
curr.add(sc.nextDouble());
}
list.add(curr);
}
At firs declare a list and collect into it all read lines:
List<String> tempHistory = new ArrayList<>();
while ((line = bufferReader.readLine()) != null) {
tempHistory.add(line);
}
Then, after bufferReader.close(); convert this tempHistory list into double[][] array.
double[][] array = new double[tempHistory.size()][];
for (int i = 0; i < tempHistory.size(); i++) {
final String currentString = tempHistory.get(i);
final String[] split = currentString.split(" ");
array[i] = new double[split.length];
for (int j = 0; j < split.length; j++) {
array[i][j] = Double.parseDouble(split[j]);
}
}
It works, but as I added in comments, this is a not so good solution, and is better to use Collections instead of array.
BTW, it works even the rows lengths are different for different lines.

convert String to Array in Java

I have a txt file like this:
5
1
3
6
9
I want to read them using java and store all of the numbers into a array.How do I do that? read them in as string and convert to arrray? (how to convert?)
the file only contain ints.
I tried read them into a string
and use this to convert
static public int[] strToA(String str)
{
int len = str.length();
int[] array = new int[len];
for (int i = 0; i < len; i++)
{
array[i] = Integer.parseInt(str.substring(i,i+1));
}
return array;
}
Scanner can help you read your file, and you can use a List or something else to store the info.
After that, you can use this List to convert your Array.
public static Integer[] read2array(String filePath) throws IOException {
List<Integer> result = new ArrayList<Integer>();
RandomAccessFile randomAccessFile = new RandomAccessFile(filePath, "r");
String line = null;
while(null != (line = randomAccessFile.readLine())) {
result.add(new Integer(line));
}
randomAccessFile.close();
return result.toArray(new Integer[result.size()]);
}
Code would be something like this. This is untested code and may have Syntax errors.
Path file = "yourfile";
// open file
try (InputStream in = Files.newInputStream(file);
BufferedReader reader =
new BufferedReader(new InputStreamReader(in))) {
String line = null;
intArr = new int[10]; // bad code could fail if file has more than 10
int i = 0;
while ((line = reader.readLine()) != null) {
intArr[i++] = Integer.parseInt(line); // parse String to int
}
} catch (IOException x) {
System.err.println(x);
}
To use List instead of array change line
intArr = new int[10];
to
List intArr = new ArrayList();
Code would be something like
List intArr = new ArrayList();
while ((line = reader.readLine()) != null) {
intArr.add(Integer.parseInt(line)); // parse String to int
}

Categories

Resources