Java - Return an integer array - java

In this function, I want to get text in the file then convert it from string to decimal values, by add this text to an array apply some loops and put the result to array of integer. While returning this integer array it gives me an error "cannot find symbol variable integerArray"
int[] inputfile () throws Exception{
BufferedReader br = null;
String sCurrentLine;
String message;
br = new BufferedReader(new FileReader("\input.txt"));
while ((sCurrentLine = br.readLine()) != null) {
message=sCurrentLine.toString();
char[] messageArray=message.toCharArray();
int[] integerArray = new int[messageArray.length];
for(int i=0; i<messageArray.length; i++)
integerArray[i] = (int)messageArray[i];
}
return integerArray;
}
How can I solve it?
Update:
I declared variable integerArray outside the while loop, but it always returns the null value, Is there any possible way to return integerArray as int values? because Arrays.toString(integerArray) returns String representation of that array
int[] inputfile () throws Exception{
BufferedReader br = null;
String sCurrentLine;
String message;
br = new BufferedReader(new FileReader("\\input.txt"));
int[] integerArray = null
while ((sCurrentLine = br.readLine()) != null) {
message=sCurrentLine.toString();
char[] messageArray=message.toCharArray();
int[] integerArray = new int[messageArray.length];
for(int i=0; i<messageArray.length; i++)
integerArray[i] = (int)messageArray[i];
}
return integerArray;

Your integerArray is inside the while loop. Declare it outside the loop and change its value inside it, then it will work.

integerArray is a local variable in the while loop , it's inaccessible outside it. Declare it outside the loop
int[] integerArray =null ;
while ((sCurrentLine = br.readLine()) != null) {
// other code
integerArray = new int[messageArray.length];
// other code
}

int[] integerArray must be declared before the loop, in order for you to be able to return it after the loop.
int[] inputfile () throws Exception{
int[] integerArray = null;
BufferedReader br = null;
String sCurrentLine;
String message;
br = new BufferedReader(new FileReader("\input.txt"));
while ((sCurrentLine = br.readLine()) != null) {
message=sCurrentLine.toString();
char[] messageArray=message.toCharArray();
integerArray = new int[messageArray.length];
for(int i=0; i<messageArray.length; i++)
integerArray[i] = (int)messageArray[i];
}
return integerArray;
}

Related

Why does bufferedreader return null on these values?

This is my code, I am using bufferedreader to read from a file. It stores the values it reads into the array, but when i try to print out the array it returns null values. Why does this happen? Code:
BufferedReader reader = new BufferedReader(new FileReader("valid file path here"));
int lines = 0;
while (reader.readLine() != null) {
lines++;
}
//declare and fill array
String[] coin_names = new String[lines];
String line;
int x = 0;
while ((line = reader.readLine()) != null) {
coin_names[x] = line;
x++;
}
for (int y = 0; y < lines; y++) {
System.out.println(coin_names[y]);
}
Why does it return null for all of the values it gets?
Here is the problem:
while (reader.readLine() != null) {
lines++;
}
Your initial while loop is consuming the entire file. A better approach would be to remove it, and instead just use a list to store the lines:
List<String> coinNames = new ArrayList<>();
String line;
int x = 0;
while ((line = reader.readLine()) != null) {
coinNames.add(line);
x++;
}
for (String name : coinNames) {
System.out.println(name);
}
While you could try to reset the reader, there is no reason why you should have to read the entire file twice just to intialize an array. Use the right data structure for the job.

Read txt file and print after split action is not printing array value

I am trying to read txt file and then store splitted value in then array, and print all txt file value. But it is not printing the values.
This is how txt file value display as below:
"1675683811","590483002"
"2002199221","876015525"
Following are my code:
String st;
BufferedReader Br = null;
File objFile = new File("C:\\DATA\\File.txt");
Br = new BufferedReader(new FileReader(objFile));
while ((st = Br.readLine()) != null) {
String value = st.replace("\"", "");
String[] arraylist = StringUtils.split(value, ",");
for (int i = 0; i <= 1; i++) {
System.out.println(arraylist[i]);
}
}
Br.close();
Maybe try to write code like below. I changed declaration of split and also way of showing values, because your way could make exception at objects arraylist:
String st;
BufferedReader Br = null;
File objFile = new File("C:\\data\\file.txt");
Br = new BufferedReader(new FileReader(objFile));
while ((st = Br.readLine()) != null) {
String value = st.replace("\"", "");
String[] arraylist = value.split(",");
for (String row : arraylist) {
System.out.println(row);
}
}
Br.close();
A small change to your code, you can just use String.split method and your for loop will always throws ArrayOutOfBound exception
String st;
BufferedReader Br = null;
File objFile = new File("/Users/a602782/input.txt");
Br = new BufferedReader(new FileReader(objFile));
while ((st = Br.readLine()) != null) {
String value = st.replace("\"", "");
String[] arraylist = value.split(",");
for (int i = 0; i <arraylist.length; i++) {
System.out.println(arraylist[i]);
}
}
Br.close();
And if you want to print each digit on each line you can loop it again inside of for loop
String st;
BufferedReader Br = null;
File objFile = new File("/Users/a602782/input.txt");
Br = new BufferedReader(new FileReader(objFile));
while ((st = Br.readLine()) != null) {
String value = st.replace("\"", "");
String[] arraylist = value.split(",");
for (int i = 0; i <arraylist.length; i++) {
System.out.println(arraylist[i]);
for (char c:arraylist[i].toCharArray()) {
System.out.println(c);
}
}
}
Br.close();

Array CompareFind Equals words only using array not array list

Have a two text file with words list. need save both file in two array.I know how to do it using list and set.. but here I want know how to do it using only arrays.Only array and no predefined functions such as Arrays.sort() or Collections.sort() can be used
no list no ArrayList or no class from Java Collection Frameworks can be used.
public class Main {
public static Set<String> setlist1= new HashSet<>();
public static String[] arrayList=new String[file1count];
public static String[] array2=new String[file2count];
public static int file1count=0;
public static int file2count=0;
public static void main(String[] args) {
try {
/*read the files*/
Scanner rf= new Scanner(new BufferedReader(new FileReader("D:\\IIT\\Project save\\New\\Inteli J\\OOPworkshop01\\file1.txt")));
Scanner rf2= new Scanner(new BufferedReader(new FileReader("D:\\IIT\\Project save\\New\\Inteli J\\OOPworkshop01\\file2.txt")));
String line;
String line2;
while(rf.hasNext()){
line=rf.nextLine();
file1count++;
}
while(rf2.hasNext()){
line2=rf2.nextLine();
file2count++;
}
rf.close();
rf2.close();
}catch(IOException e){
System.out.println(e);
}
}
}
The problem with using arrays is that you don't know in advance what length to allocate.
You basically have two options:
read each file twice
allocate an array of some initial length, and reallocate is as needed (that's what an ArrayList does.)
Second option: let's have a method readFile that reads all the lines from a file and returns an array:
public static String[] readFile(String fileName) throws IOException {
try (Reader reader = new FileReader(fileName);
BufferedReader in = new BufferedReader(reader)) {
String[] lines = new String[10]; // start with 10
int count = 0;
String line;
while ((line = in.readLine()) != null) {
if (count >= lines.length) {
lines = reallocate(lines, count, 2*lines.length);
}
lines[count++] = line;
}
if (count < lines.length) {
// reallocate to the final length;
lines = reallocate(lines, count, count);
}
return lines;
}
}
private static String[] reallocate(String[] lines, int count,
int newLength) {
String[] newArray = new String[newLength];
for (int i = 0; i < count; ++i) {
newArray[i] = lines[i];
}
lines = newArray;
return lines;
}
BufferedReader reader1 =
new BufferedReader(new FileReader("D:\\IIT\\Project save\\New\\Inteli J\\OOPworkshop01\\file1.txt"));
BufferedReader reader2 =
new BufferedReader(new FileReader("D:\\IIT\\Project save\\New\\Inteli J\\OOPworkshop01\\file2.txt"));
String line1 = reader1.readLine();
String[] array1 = new String[10000000];
String[] array2 = new String[10000000];
String line2 = reader2.readLine();
boolean areEqual = true;
int lineNum = 1;
while (line1 != null || line2 != null) {
if (line1 == null || line2 == null) {
areEqual = false;
break;
} else if (!line1.equalsIgnoreCase(line2)) {
areEqual = false;
break;
}
if (line1 != null) {
array1[lineNum] = line1;
}
if (line1 != null) {
array2[lineNum] = line2;
}
line1 = reader1.readLine();
line2 = reader2.readLine();
lineNum++;
}
if (areEqual) {
System.out.println("Same content.");
} else {
System.out.println("different content");
}
reader1.close();
reader2.close();
You can simply try above code.
Here I had used only WHILE loop, BufferedReader and FileReader.

Java Sort Data From A File Using Arrays

I have to write a method that reads the file integers.txt and return an array of integers. I have to convert each line of data from text to an integer.
However, I cannot figure out why I am getting an error when I try to assign the array x to the integers within the file and when I convert the data to integers. I am also getting an error with my return statement.
public static int[] processFile (String filename) throws IOException, FileNotFoundException {
double number;
double average;
BufferedReader inputReader = new BufferedReader (new InputStreamReader(new FileInputStream("integers.txt")));
String line;
while ((line = inputReader.readLine()) != null) {
number = Int.parseInt(line);
int[] x = (number);
inputReader.close();
}
return int[] x;
}
There are multiple issues with your code:
You are using return int[] x; instead of simply return x;
x is only assigned inside the while, so you can't return it outside
x = (number); isn't a correct method for adding a value to the array
The int[] x; is never initialized
You use double number at the top of the method, but then assign it with an int here: number = Int.parseInt(line);
My suggestions is to use this instead, which will give an ArrayList<int> as output.
public static ArrayList<Integer> processFile (String filename) throws IOException, FileNotFoundException
{
BufferedReader inputReader = new BufferedReader (new InputStreamReader(new FileInputStream("integers.txt")));
String line;
ArrayList<Integer> list = new ArrayList<>();
while ((line = inputReader.readLine()) != null) {
int number = Int.parseInt(line);
list.add(number);
}
inputReader.close();
return list;
}
If you really need an int[] instead, you'll have to give it a size first like this: int[] x = new int[size_here]; For example:
public static int[] processFile (String filename) throws IOException, FileNotFoundException
{
BufferedReader inputReader = new BufferedReader (new InputStreamReader(new FileInputStream("integers.txt")));
String line;
int[] array = new int[100]; // Example size of 100
int index = 0;
while ((line = inputReader.readLine()) != null) {
int number = Int.parseInt(line);
array[index++] = number;
}
inputReader.close();
return array;
}
And if you need an int[] instead, AND don't know the size beforehand, try this instead:
public static int[] processFile (String filename) throws IOException, FileNotFoundException
{
BufferedReader inputReader = new BufferedReader (new InputStreamReader(new FileInputStream("integers.txt")));
String line;
ArrayList<Integer> list = new ArrayList<>();
while ((line = inputReader.readLine()) != null) {
int number = Int.parseInt(line);
list.add(number);
}
inputReader.close();
return convertIntegers(list);
}
public static int[] convertIntegers(List<Integer> integers)
{
int[] ret = new int[integers.size()];
Iterator<Integer> iterator = integers.iterator();
for (int i = 0; i < ret.length; i++)
{
ret[i] = iterator.next().intValue();
}
return ret;
}
Firstly it's Integer.parseInt()
number = Int.parseInt(line);
int[] x = (number);
number will contain a single int not an array of ints. so this int[] x = (number); assignment is wrong.
return int[] x; this is also invalid syntax.
There are a few problems here. To answer your question, you can't assign an int to an int array. Next, unless you entered your code incorrectly, you are closing the inputReader inside the while loop that is doing the reading. Also, you are returning int[] x. That is wrong. Return x.

Replace a newline character stored in an array of Strings [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How do I compare strings in Java?
Consider the following 2D array of Strings a[5][5],
I store three values in the first three blocks in the array "a".
When I print my array, I get the following output.
ABC
null
DEF
null
These values are present in a file and I retrieve the values and store them in an array of strings.
The file ("file.txt")looks like this,
A B C
D E F
Here is my code,
Declaration:
static String [][] a= new String [4][4];
public static String newline = System.getProperty("line.separator");
private static int i,j;
Main code:
i=j=0;
FileInputStream fin;
fin = new FileInputStream("file.txt");
DataInputStream in = new DataInputStream (fin);
BufferedReader br = new BufferedReader (new InputStreamReader (in));
while((c = (char)br.read()) != (char)-1)
{
if (c != ' ' && c != (char)'\n')
{
a[i][j] = Character.toString(c);
j++;
}
else if (c == '\n')
{
i++;
j = 0;
}
}
for (int i=0;i<5;i++)
{
for (int j=0;j<5;j++)
{
if (newline.equals(a[i][j]))
{
mainArray[i][j] = null;
}
}
}
Here is how I print my array,
for (int i=0;i<5;i++)
{
for (int j=0;j<5;j++)
{
System.out.print(a[i][j]);
}
System.out.println("");
}
My desired output should be,
ABCnullnull
DEFnullnull
Is there a better way to work on this problem??
BufferedReader has a readLine() method that will return a string with all the chars preceding the \n or \r. It also returns null at the end of the stream.
FileInputStream fin;
fin = new FileInputStream("file.txt");
DataInputStream in = new DataInputStream (fin);
BufferedReader br = new BufferedReader (new InputStreamReader (in));
List<String> list = new ArrayList<String>();
String line;
while ((line= br.readLine())!=null)
{
list.add(line);
}
This will cope with any number of returns and arbitrary length strings.
Or if you must have each line as and array
FileInputStream fin;
fin = new FileInputStream("file.txt");
DataInputStream in = new DataInputStream(fin);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
List<char[]> list = new ArrayList<char[]>();
String line;
while ((line = br.readLine()) != null) {
if(!line.isEmpty()) list.add(line.toCharArray());
}
Reading your file should result in a List size of two each containing and array of 5 chars. ['A',' ','B',' ','C'] then ['D',' ','E',' ','F']
Try
public static String newline = System.getProperty("line.separator");
for (int i=0;i<5;i++)
{
if (newline.equals(a[i]))
{
a[i] = null;
}
}
EDITED ANSWER:
From reading your responses and looking at what your expected output is, you may be better off doing something like this...
pseudo-code
read entire line into String array index
Before printing, check length of String (a[i].length)
If length is less than 5, add 'null' to the end of the String for every character less than 5
Thus:
if(a[i].length < 5)
{
int index = 5 - a[i].length;
for( ; index > 0; index --)
{
a[i].concat("null");
}
}
ORIGINAL ANSWER............
Not sure if my comment was sent to you or not. You might just be indexing too far out.
Try
for(int i = 0; i < 4; i++)
System.print(a[i]);

Categories