Java - Problems with returning an integer array - java

I'm trying to read a .txt file called Heights.txt, which contains a string of numbers, each separated by a ":". The method produces one error that I can't seem to figure out.
It says that "the method must return a result of type int[]", at the very first line of this code.
I don't understand why it says this, as integerHeightDataPoints should be an integer array at that point, and should be able to be returned to a int[] method?
public static int[] readFile(){
BufferedReader br = null;
String dataPoints;
try {
br = new BufferedReader(new FileReader("Path\\Heights.txt"));
}
catch(IOException e) {
System.out.println("Please enter data first");
System.exit(0);
}
try {
while((dataPoints = br.readLine()) != null) {
if (dataPoints.contains(":")) {
String[] heightDataPoints = dataPoints.split(":");
int[] integerHeightDataPoints = new int[heightDataPoints.length];
for (int i = 0; i < integerHeightDataPoints.length; i++) {
integerHeightDataPoints[i] = Integer.parseInt(heightDataPoints[i]);
}
return integerHeightDataPoints;
}
}
}
catch (IOException e) {
System.out.println("Error reading file");
e.printStackTrace();
}
}

It's because you don't return anything in second IOException case or (as #Exception_al mentioned) when while never triggers.
public static int[] readFile() {
BufferedReader br = null;
String dataPoints;
try {
br = new BufferedReader(new FileReader("/tmp/file1"));
} catch (IOException e) {
System.out.println("Please enter data first");
System.exit(0);
}
int[] integerHeightDataPoints = new int[0];
try {
while ((dataPoints = br.readLine()) != null) {
if (dataPoints.contains(":")) {
String[] heightDataPoints = dataPoints.split(":");
integerHeightDataPoints = new int[heightDataPoints.length];
for (int i = 0; i < integerHeightDataPoints.length; i++) {
integerHeightDataPoints[i] = Integer.parseInt(heightDataPoints[i]);
}
return integerHeightDataPoints;
}
}
} catch (IOException e) {
System.out.println("Error reading file");
e.printStackTrace();
}
return integerHeightDataPoints;
}

Related

How return a multidimensional arrayList in java?

I want to create a multidimensional array and pass it as a parameter in a method and then fill the arrayList with elements and return the new version of the arrayList to be able to use that array in different classes but I get java.lang.NoSuchMethodError: I think the problem is about the way i return the array. I searched but I could not find . How can I do it correctly?
here is my code;
public test{
public static List<List<String>> 2Darray=new ArrayList<List<String>>(); // TE ERROR IN THIS LINE
public List<List<String>> fillArray(List<List<String>> array){
BufferedReader in = null;
ArrayList<String> row = new ArrayList<String>();
try {
in = new BufferedReader(new FileReader("sampleFile.txt"));
String read = null;
while ((read = in.readLine()) != null) {
String[] splited = read.split("\\s+");
for(int i=0; i<splited.length ; i++){
row.add(splited[i]);
}
array.add(row);
}
} catch (IOException e) {
System.out.println("There was a problem: " + e);
e.printStackTrace();
} finally {
try {
in.close();
} catch (IOException e) {
}
return array;
}
A little tinkering (just getting it to compile) results in this which seems not to have a problem. Perhaps your issue is elsewhere.
public List<List<String>> fillArray(List<List<String>> array) {
BufferedReader in = null;
ArrayList<String> row = new ArrayList<String>();
try {
in = new BufferedReader(new FileReader("sampleFile.txt"));
String read = null;
while ((read = in.readLine()) != null) {
String[] splited = read.split("\\s+");
for (int i = 0; i < splited.length; i++) {
row.add(splited[i]);
}
array.add(row);
}
} catch (IOException e) {
System.out.println("There was a problem: " + e);
e.printStackTrace();
} finally {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return array;
}
BTW: You should really use try with resources - it is much clearer.
Modified your code a bit so that it compiled, and replaced the reading from a text file to reading a string. There were several issues, but it seems to work. Give it a try.
The main problems I noticed were mismatching curly braces, and starting a variable name with a number.
import java.util.*;
import java.io.*;
public class Main {
public static List<List<String>> array2D = new ArrayList<List<String>>();
public List<List<String>> fillArray(List<List<String>> array) {
BufferedReader in = null;
ArrayList<String> row = new ArrayList<String>();
try {
String str = "Some test text";
InputStream is = new ByteArrayInputStream(str.getBytes());
//in = new BufferedReader(new FileReader("sampleFile.txt"));
in = new BufferedReader(new InputStreamReader(is));
String read = null;
while ((read = in.readLine()) != null) {
String[] splited = read.split("\\s+");
for(int i=0; i<splited.length ; i++) {
row.add(splited[i]);
}
array.add(row);
}
}
catch (IOException e) {
System.out.println("There was a problem: " + e);
e.printStackTrace();
}
finally {
try {
in.close();
}
catch (IOException e) {
}
}
return array;
}
public static void main(String[] args) {
Main main = new Main();
List<List<String>> test = main.fillArray(array2D);
for(int i = 0; i < test.size(); i++) {
for(int j = 0; j < test.get(i).size(); j++) {
System.out.println(test.get(i).get(j));
}
}
}
}

String cannot be converted to array

I have a program that reads in a file using a filename specified by the user.
All file contents must be read and stored in the array. I seem to have done the IO Correctly besides this error. I understand what the error is but not sure how to correct.
EDIT: The array is already defined in the file.
Zoo.java:284: error: incompatible types: String cannot be converted to
Animals
animals[ j ] = bufferedReader.readLine();
Here is my code for the readFile Submodule:
public String readFile(Animals[] animals)
{
Scanner sc = new Scanner(System.in);
String nameOfFile, stringLine;
FileInputStream fileStream = null;
BufferedReader bufferedReader;
InputStreamReader reader;
System.out.println("Please enter the filename to be read from.");
nameOfFile = sc.nextLine();
try
{
constructed = true;
fileStream = new FileInputStream(nameOfFile);
bufferedReader = new BufferedReader(new InputStreamReader(fileStream));
while((stringLine = bufferedReader.readLine()) != null)
{
for(int j = 0; j < animals.length; j++)
{
animals[j] = bufferedReader.readLine();
}
}
fileStream.close();
}
catch(IOException e)
{
if(fileStream != null)
{
try
{
fileStream.close();
}
catch(IOException ex2)
{
}
}
System.out.println("Error in file processing: " + e.getMessage();
}
}
Thanks for the help.
animals is array of Animals, but bufferedReader.readLine() reads line. You should convert it to Animal. I don't see definition of your class Animals, but, I think, there should be constructor that takes String as argument.
So, If i'm right, you should basically write:
animals[j] = new Animals(bufferedReader.readLine());
Lots of problems in your code. Starting with the method's input. Also reading from file.
public static void main(String[] args) {
// TODO code application logic here
for(String entry : readFile())
{
System.out.println(entry);
}
}
static public String[] readFile()
{
Scanner sc = new Scanner(System.in);
InputStreamReader reader;
System.out.println("Please enter the filename to be read from.");
String nameOfFile = sc.nextLine();
try(BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream(nameOfFile))); )
{
//constructed = true; why?
String stringLine;
ArrayList<String> arraylist = new ArrayList();
while((stringLine = bufferedReader.readLine()) != null)
{
arraylist.add(stringLine);
}
return arraylist.toArray(new String[0]);
}
catch (FileNotFoundException ex)
{
Logger.getLogger(Filetoarray.class.getName()).log(Level.SEVERE, null, ex);
}
catch (IOException ex)
{
Logger.getLogger(Filetoarray.class.getName()).log(Level.SEVERE, null, ex);
}
return null;
}

Is it possible to read data from file and store it into 2d Array,when we don't know the number of line in the file,in java

I have to read data from file Here is data and want plot a graph vs thick(column 1 in data) and alpha(column 3) for every model. Every model has 7 line data,the last that start with 0 not required. Here is my code. it works but i don't think it is good code.please, suggest me better way to do the same.
public class readFile {
public static int showLines(String fileName) {
String line;
int currentLineNo = 0;
BufferedReader in = null;
try {
in = new BufferedReader (new FileReader(fileName));
//read until endLine
while(((line = in.readLine()) != null)) {
if (!line.contains("M") && !line.contains("#") && !line.trim().startsWith("0")) {
//skipping the line that start with M, # and 0.
currentLineNo++;
}
}
} catch (IOException ex) {
System.out.println("Problem reading file.\n" + ex.getMessage());
} finally {
try { if (in!=null) in.close(); } catch(IOException ignore) {}
}
return currentLineNo;
}
//Now we know the dimension of matrix, so storing data into matrix
public static void readData(String fileName,int numRow) {
String line;
String temp []=null;
String data [][]=new String[numRow][10];
int i=0;
BufferedReader in = null;
try {
in = new BufferedReader (new FileReader(fileName));
//read until endLine
while(((line = in.readLine()) != null)) {
if (!line.contains("M") && !line.contains("#") && !line.trim().startsWith("0")) {
temp=(line.trim().split("[.]"));
for (int j = 0; j<data[i].length; j++) {
data[i][j] =temp[j];
}
i++;
}
}
// Extract one column from 2d matrix
for (int j = 0; j <numRow; j=j+6) {
for (int j2=j; j2 <6+j; j2++) {
System.out.println(Double.parseDouble(data[j2][0])+"\t"+Double.parseDouble(data[j2][2]));
//6 element of every model, col1 and col3
// will add to dataset.
}
}
} catch (IOException ex) {
System.out.println("Problem reading file.\n" + ex.getMessage());
} finally {
try { if (in!=null) in.close(); } catch(IOException ignore) {}
}
}
//Main Method
public static void main(String[] args) {
//System.out.println(showLines("rf.txt"));
readData("rf.txt",showLines("rf.txt") );
}
}
as johnchen902 implies use a list
List<String> input=new ArrayList<String>();
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
input.add(line);
}
br.close();
int N=input.get(0).split(",").size(); // here add your delimiter
int M=input.size();
String[][] data=new String[M][N]
for (int i=0;i<M;i++){
String[] parts = string.split("-");
for (int k=0;k<n;k++){
data[i][k]=parts[k];
}
}
something like that
hope it helps. plz put more effort into asking the question. Give us the needed Input files, and the Code you came up with until now to solve the problem yourself.

Save/Read File in android

I want to save to a file in android , Some of my arrayList that will be deleted after that.I already have two methods to write/read from android file here but the problem is I want the two methods do that:
the first method must save the element of arraylist then if I call it again it will not write the new element in the same line but write it in another line
The second must read a line (for example I give to the method which line and it returns what the lines contains)
The file looks like that :
firstelem
secondelem
thridelem
anotherelem
another ..
is this possible to do in android java?
PS: I don't need database.
Update
This is My methods :
private void writeToFile(String data) {
try {
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(openFileOutput("config.txt", Context.MODE_PRIVATE));
outputStreamWriter.write(data);
outputStreamWriter.close();
}
catch (IOException e) {
Log.e("Exception", "File write failed: " + e.toString());
}
}
private String readFromFile() {
String ret = "";
try {
InputStream inputStream = openFileInput("config.txt");
if ( inputStream != null ) {
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String receiveString = "";
StringBuilder stringBuilder = new StringBuilder();
while ( (receiveString = bufferedReader.readLine()) != null ) {
stringBuilder.append(receiveString);
// stringBuilder.append("\\n");
}
inputStream.close();
ret = stringBuilder.toString();
}
}
catch (FileNotFoundException e) {
Log.e("login activity", "File not found: " + e.toString());
} catch (IOException e) {
Log.e("login activity", "Can not read file: " + e.toString());
}
return ret;
}
Using the save method you linked to you can create the text to save with a StringBuilder:
public String makeArrayListFlatfileString(List<List<String>> listOfLists)
{
StringBuilder sb = new StringBuilder();
if (!listOfLists.isEmpty()) {
// this assumes all lists are the same length
int listLengths = listOfLists.get(0).size();
for (int i=0; i<listLengths; i++)
{
for (List<String> list : listOfLists)
{
sb.append(list.get(i)).append("\n");
}
sb.append("\n"); // blank line after column grouping
}
}
return sb.toString();
}
To parse the contents from that same file (again assuming equal length lists and a String input):
public List<List<String>> getListOfListsFromFlatfile(String data)
{
// split into lines
String[] lines = data.split("\\n");
// first find out how many Lists we'll need
int numberOfLists = 0;
for (String line : lines){
if (line.trim().equals(""))
{
// blank line means new column grouping so stop counting
break;
}
else
{
numberOfLists++;
}
}
// make enough empty lists to hold the info:
List<List<String>> listOfLists = new ArrayList<List<String>>();
for (int i=0; i<numberOfLists; i++)
{
listOfLists.add(new ArrayList<String>());
}
// keep track of which list we should be adding to, and populate the lists
int listTracker = 0;
for (String line : lines)
{
if (line.trim().equals(""))
{
// new block so add next item to the first list again
listTracker = 0;
continue;
}
else
{
listOfLists.get(listTracker).add(line);
listTracker++;
}
}
return listOfLists;
}
For writing, just as Illegal Argument states - append '\n':
void writeToFileWithNewLine(String data) {
try {
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(openFileOutput("config.txt", Context.MODE_PRIVATE));
outputStreamWriter.write(data + "\n");
outputStreamWriter.close();
}
catch (IOException e) { /* handle exception */ }
}
For reading (just the idea, in practice you should read the file only once):
String readLine(final int lineNo) {
InputStream in = new FileInputStream("file.txt");
ArrayList<String> lines = new ArrayList<String>();
try {
InputStreamReader inReader = new InputStreamReader(in);
BufferedReader reader = new BufferedReader(inReader);
String line;
do {
line = reader.readLine();
lines.add(line);
} while(line != null);
} catch (Exception e) { /* handle exceptions */ }
finally {
in.close();
}
if(lineNo < lines.size() && lineNo >= 0) {
return lines.get(lineNo);
} else {
throw new IndexOutOfBoundsException();
}
}

How to get a specific value from a text file

I have a .txt file:
80,90,100,110,120,130,140,150,160
100,20,22,24,26,28,26,28,29,27
110,30,32,34,36,37,39,37,39,40
120,40,41,42,44,45,46,48,47,49
which represents a table with prices for blinds, the first row is the width of the blind and the first column without 80 is the height. The rest of the numbers are the prices.
I already did this using c# but in java I have no idea what to do, in c# my code looks like this and everything is fine. Can somebody show me the same thing in java?
theWidth and theHeight are text fields where I have to type the dimensions.
string[] lines = File.ReadAllLines(#"tabel.txt");
string[] aux = lines[0].Split(',');
for (int i = 0; i < aux.Length-1; i++)
{
if (aux[i] == theWidth.ToString())
{
Console.WriteLine(aux[i]);
indiceLatime = i;
}
}
for (int i = 1; i < lines.Length; i++)
{
aux = lines[i].Split(',');
if (aux[0] == theHeight.ToString())
{
showPrice.Text = aux[indiceLatime + 1];
}
}
In java I tried something like this:
try {
BufferedReader inputStream = new BufferedReader(new FileReader("tabel.txt"));
int theWidth = 90;
int theHeight = 100;
int indiceLatime = 0;
String line;
try {
while ((line = inputStream.readLine()) != null) {
String[] aux = line.split(",");
for (int i = 0; i < aux.length; i++) {
if (aux[i].equals(Integer.toString(theWidth))) {
indiceLatime = i;
}
}
for (int i = 1; i < aux.length; i++) {
if (aux[0].equals(Integer.toString(theHeight))) {
System.out.println("price: " + aux[indiceLatime]);
}
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
So the price is in theHeight's row of theWidth's index which I am trying to get somehow. Is there somebody who can show me how can I get the correct number(price) out from the row?
You can use FileReader like this:
try {
br = new BufferedReader(new FileReader(filePath));
while ((line = br.readLine()) != null) {
// code here to handle the current readed line
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
[Edit]
Regarding to your updates, i have edit you code, please check it.
int widthIndex = 90;
int hightIndex = 100;
int indiceLatime = 0;
boolean lookForWidth = true;
try {
BufferedReader br = new BufferedReader(new FileReader("table.txt"));
String line = "";
while ((line = br.readLine()) != null) {
String[] aux = line.split(",");
if(lookForWidth) {// this flag to look for width only at the first time.
for (int i = 0; i < aux.length; i++) {
if(widthIndex == Integer.parseInt(aux[i].trim())) {
indiceLatime = i;
lookForWidth = false;
continue;
}
}
}
for (int i = 0; i < aux.length; i++) {
if(hightIndex == Integer.parseInt(aux[0])) {
System.out.println(aux[indiceLatime]);
break;
}
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Try like this:
public static void main(String[] args) throws FileNotFoundException {
String filePath = <Your file Path>;
try {
BufferedReader br = new BufferedReader(new FileReader(filePath ));
String line = br.readLine();
System.out.println(line);
while (line != null || !line.equals(null)) {
System.out.println(line);
line=br.readLine();
}
} catch (Exception e) {
}
}

Categories