I try to convert a file to an array of integers, do not know where my mistake is that when I print the array empty array throws
I leave my method , thanks you
public int[] ConvertToArray(File xd) throws IOException {
String sCadena;int i=0;
int[]array;
FileReader fr = new FileReader(xd);
BufferedReader bf = new BufferedReader(fr);
int lNumeroLineas = 0;
while ((sCadena = bf.readLine())!=null) {
lNumeroLineas++;
}
array = new int[lNumeroLineas];
while ((sCadena = bf.readLine())!=null) {
lNumeroLineas++;
array[i]=Integer.parseInt(sCadena);
i++;
}
for (int j = 0; j < array.length; j++) {
System.out.println(array[i]);
}
return array;
}
You are already at the end of file after your first while loop completes.
So reading from BufferedReader object bf again after first while loop ends will always give you null(End of file) and second iteration will never run.
Also in the for loop you are printing array[i] however for loop is iterating over j variable
You can do it like this with help of ArrayList:
public int[] ConvertToArray(File xd) throws IOException {
String sCadena;
ArrayList<Integer> array = new ArrayList();
FileReader fr = new FileReader(xd);
BufferedReader bf = new BufferedReader(fr);
int lNumeroLineas = 0;
while ((sCadena = bf.readLine())!=null) {
lNumeroLineas++;
array.add(Integer.parseInt(sCadena.trim())); //always recomended to trim(); to remove trailing whitespaces.
}
for (int j = 0; j < array.size(); j++) {
System.out.println(array.get(j));
}
return covertIntegers(array);
}
Edited: If you want to send int[] instead of ArrayList<Integer> without using any external libraries.
public static int[] convertIntegers(List<Integer> integers)
{
int[] ret = new int[integers.size()];
for (int i=0; i < ret.length; i++)
{
ret[i] = integers.get(i).intValue();
}
return ret;
}
You are reading the file with two loops but open only once. Reopen the file reader before the second while and it will work.
Related
I am not sure where to put my finally block in the linked class I am working on.
I am a beginner so I am still very new to this.
https://pastebin.com/Bu0k6NtL
public class CrimesArray {
static int columns;
static int row;
String[][] crime2DArray;
public void saveFileTo2DArray(String commandArgs) {
crime2DArray = new String[row][columns]; //Constructs Array
String fileLine; //Variable to hold tokens in
int i=0; //Variable to increment minCapacity
try {
BufferedReader inputStream = new BufferedReader(new FileReader(commandArgs)); //A reader to read the commandArgs file and this reader is put into a buffered reader for efficiency
while ((fileLine = inputStream.readLine()) != null) { //While there is still lines to be read
addTo2DArray(fileLine.split(","), ++i); //Passes in a String array where it splits every "," and a counter to increment minCapacity
}
//Add's the files contents to a 2D array, it does this by incrementally building our crime2DArray and assigning tempArrays values to it
public void addTo2DArray(String[] tmpArray, int minCapacity) {
if((minCapacity > row)) {
row = (row * 3)/2 + 1;
String[][] newArray = new String[row][columns];
for(int i=0; i<crime2DArray.length; i++) {
for(int j=0; j<crime2DArray[i].length; j++) {
newArray[i][j]=crime2DArray[i][j];
}
}
crime2DArray = newArray;
}
crime2DArray[minCapacity-1] = tmpArray;
}
Here is a guide for try / finally syntax in Java language: Java: try + finally
The input my program gets are a few strings of characters which represents rows in a matrix. I would like to put the columns of this matrix in a LinkedHashMap, but without first storing everything in an array and then construct the columns and put them in the LinkedHashMap. The idea is that this should be done as fast as possible.
Example:
Input:
abfad
grgaa
rtwag
The strings that should be saved in a LinkedHashMap are:
agr
brt
fgw
aaa
dag
Edit:
This is how my program does it right now:
String[][] array = new String[n][m];
LinkedHashMap<Integer, String> map = new LinkedHashMap<Integer, String>();
for (int i = 0; i < n; i++) {
array[i] = br.readLine().split("");
}
for (int i = 0; i < m; i++) {
String column = "";
for (int j = 0; j < n; j++) {
column += array[j][i];
}
map.put(i, column);
}
I am not sure why this is downvoted.
It's an interesting problem that you should perhaps ask a little better.
Does it help if you think of this as a real-time transform of a matrix? What should happen when you read the first line? What should happen for each subsequent line? We are assuming that all lines have same length, otherwise we'll need to specify what happens when they are not.
After you have tried on your own, maybe you can take a look below. I have not used LinkedHashMap there, also I have used the mutable StringBuilder. But you can easily modify it to use the data structure of your choice.
public class RealTimeTransform {
public static void main(String[] args) throws IOException {
Map<Integer, StringBuilder> columns = new HashMap<>();
readColumnsFromRows(columns, System.in);
System.out.println(columns.values());
}
private static void readColumnsFromRows(Map<Integer, StringBuilder> columns, InputStream in) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
int rc = 0;
String row;
while ((row = reader.readLine()) != null) {
if (rc == 0) {
for (int i = 0; i < row.length(); i++) {
columns.put(i, new StringBuilder(10).append(row.charAt(i)));
}
} else {
for (int i = 0; i < row.length(); i++) {
columns.get(i).append(row.charAt(i));
}
}
rc += 1;
}
}
}
This prints:
aman
plan
yess
[apy, mle, aas, nns]
per your specification.
I want to read and save the content of the file in a 2d array, but I don't know the size of the file, because the program should read different files. So there is the first problem after "new char". I searched for the problem and found that "matrix[x][y]=zeile.charAt(x);"
should be right, but that throws the error "NullPointerException" when I write any number into the first brackets of new char.
Could somebody explain and give some ideas oder solutions? Thank you :)
import java.io.*;
class Unbenannt
{
public static void main(String[] args) throws IOException
{
FileReader fr = new FileReader("Level4.txt");
BufferedReader br = new BufferedReader(fr);
String zeile = br.readLine();
char [][] matrix = new char [][];
while(zeile != null )
{
int y = 0;
for(int x = 0; x < zeile.length(); x++) {
matrix[x][y] = zeile.charAt(x);
}
y++;
} System.out.print(matrix);
br.close();
}
}
Arrays are stored as blocks in memory in order to achieve O(1) operations, which is why you need to define their size during definition. If you insist on arrays (rather than a dynamic ADT such as List), you'll need to know the dimensions in advance.
What you could do is store the file lines temporarily in a list and find out the maximum line length, i.e.:
List<String> lines = new ArrayList<String>();
String zeile = null;
int max = 0;
while ((zeile = br.readLine()) != null) {
lines.add(zeile);
if (zeile.length() > max)
max = zeile.length();
}
char[][] matrix = new char[lines.length()][max];
// populate the matrix:
for (int i = 0; i < lines.length(); i++) {
String line = lines.get(i);
for (int j = 0; j < line.length(); j++) {
matrix[i][j] = line.charAt(j);
}
}
Note that since char is a primitive, you'll be initialized with the default value 0 (the integer, not the character!) in every cell of the inner array, so for lines which are shorter than the others, you'll have trailing zero characters.
you initialize the matrix (char [][]) but you never initialize any of the inbound arrays. This leads to the NullPointerException.
In addition your 'while' condition looks invalid, seems you only are reading the first line of your file here > your code will never complete and read the first line over and over again
Thank you all! It works! But there is still one problem. I changed lines.length() into lines.size(), because it doesn't work with length. The problem is the output. It shows for example: xxxx xxxx instead of "xxx" and "x x" and "xxx" among each other.
How can I build in a line break?
my programcode is:
import java.io.*;
import java.util.ArrayList;
class Unbenannt
{
public static void main(String[] args) throws IOException
{
FileReader fr = new FileReader("Level4.txt");
BufferedReader br = new BufferedReader(fr);
ArrayList<String> lines = new ArrayList<String>();
String zeile = null;
int max = 0;
while ((zeile = br.readLine()) != null) {
lines.add(zeile);
if (zeile.length() > max)
max = zeile.length();
}
char [][] matrix = new char[lines.size()][max];
for(int i = 0; i < lines.size(); i++) {
String line = lines.get(i);
for(int j = 0; j < line.length(); j++) {
matrix[i][j] = line.charAt(j);
System.out.print(matrix[i][j]);
}
}
br.close();
}
}
I'm supposed to sort a char array and print it in descending order. Should be simple, however, I'm not getting the output I want. All solutions around the internet tells me Arrays.sort is okay to use, but am I supposed to use another method? Or am I overlooking something?
public class mainClassTextFile {
public static void main(String[] args) throws IOException {
FileReader fileReader = new FileReader("file.txt");
String fileContents = "";
int i;
int loopcount = 0;
int count = 0;
while((i = fileReader.read())!=-1){
char ch = (char)i;
fileContents = fileContents + ch;
}
char[] ch=fileContents.toCharArray();
for(int n = 0; n < ch.length; n++) {
boolean addCharacter=true;
for(int t = 0; t < n; t++) {
if (ch[n] == (fileContents.charAt(t)))
addCharacter=false;
}
if (addCharacter) {
for(int j = 0; j < fileContents.length(); j++) {
if(ch[n]==fileContents.charAt(j))
count=count+1;
}
Arrays.sort(ch);
System.out.print(ch[n] + ": "+(count));
System.out.println();
count=0;
loopcount++;
}
}
}
}
The output is supposed to be all the characters in the text, counted and sorted, however this is the result:
: 3339
X: 4
X: 4
X: 4
X: 4
[: 2
]: 2
If I // Arrays.sort() then I get all the characters in the text file counted correctly, however they are neither sorted or in descending order!
Your for-loop really doesnot make sense to me but if you want to read string from a file convert it to charArray and sort it you can do it this way
FileReader fileReader = new FileReader("yourFile.txt");
StringBuilder br = new StringBuilder();
while(true){
int ch = fileReader.read();
if(ch==-1)
break;
char chArr = (char)ch;
br.append(chArr);
}
char[] ch=br.toString().replaceAll("\\s+", "").toCharArray(); //removed all spaces
System.out.println(Arrays.toString(ch));
Arrays.sort(ch);
System.out.println("After sorting : "+Arrays.toString(ch)); // ascending order
for(int i = ch.length - 1; i >= 0; i--)
System.out.println(arr[i]); //descending order
Your code had a lot of mistakes, including conceptual ones; so instead of getting into detailed explanations on how it could be corrected, I submit code which works and which I tried to make as similar to yours:
public static void main(String[] args) throws IOException {
final String fileContents;
try (Scanner sc = new Scanner(new File("file.txt"))) {
fileContents = sc.useDelimiter("\\Z").next();
}
final char[] ch = fileContents.toCharArray();
Arrays.sort(ch);
int prevChar = -1, count = 0;
for (int i = 0; i < ch.length; i++) {
if (ch[i] != prevChar) {
if (count > 0) System.out.println((char)prevChar + ": "+count);
count = 1;
prevChar = ch[i];
} else count++;
}
if (count > 0) System.out.println((char)prevChar + ": "+count);
}
Note that I took the liberty to completely change the routine to load the whole file as a String. This is because I regard file reading as a side concern here.
The loop works by going through the sorted array and emitting count each time it encounters a character different from the previous one. In the end we have a duplicated line of code which prints the final character.
what makes it only be able to input 10*10 text files
package game;
import java.io.*;
import java.util.*;
public class Level {
static public void main(String[] args) throws IOException {
File f = new File("Data1.txt");
int[][] m = Map(f);
for (int x = 0; x < m.length; x++) {
for (int y = 0; y < m[x].length; y++) {
System.out.print(m[x][y]);
}
System.out.println();
}
}
public static int[][] Map(File f) throws IOException {
ArrayList line = new ArrayList();
BufferedReader br = new BufferedReader(new FileReader(f));
String s = null;
while ((s = br.readLine()) != null) {
line.add(s);
}
int[][] map = new int[line.size()][];
for (int i = 0; i < map.length; i++) {
s = (String) line.get(i);
StringTokenizer st = new StringTokenizer(s, " ");
int[] arr = new int[st.countTokens()];
for (int j = 0; j < arr.length; j++) {
arr[j] = Integer.parseInt(st.nextToken());
}
map[i] = arr;
}
return map;
}
}
if i put in a text file that is
10*10 or less characters it works
otherwise it comes out with a numberformatexception
fixed
package game;
import java.io.*;
import java.util.*;
public class Level {
static public void main(String[] args) throws IOException {
File f = new File("Data1.txt");
int[][] m = Map(f);
for (int x = 0; x < m.length; x++) {
for (int y = 0; y < m[x].length; y++) {
System.out.print(m[x][y]);
}
System.out.println();
}
}
public static int[][] Map(File f) throws IOException {
ArrayList line = new ArrayList();
BufferedReader br = new BufferedReader(new FileReader(f));
String s = null;
while ((s = br.readLine()) != null) {
line.add(s);
}
int[][] map = new int[line.size()][];
for (int i = 0; i < map.length; i++) {
s = (String) line.get(i);
char[] m = s.toCharArray();
String[] n = new String[m.length];
for (int t = 0; t<m.length;t++)
{
n[t] = ""+m[t];
}
int[] arr = new int[m.length];
for (int j = 0; j < arr.length; j++) {
arr[j] = Integer.parseInt(n[j]);
}
map[i] = arr;
}
return map;
}
}
Contrary to notes in the comments, your program seems to work with large files, and with long lines, as long as there are enough spaces.
I think your issue is actually that whenever the text file has a token with more than 10 characters it throws a NumberFormatException.
That would be because Integer.MAX_INT is 2147483647, which has 10 characters when written as a String, and Integer.parseInt just can't handle more digits than that.
You're splitting on space and expecting everything to parse as an integer, and some of your numbers are too big for Java's integer data type.
Int's max value is: 2,147,483,647 or 2147483647 without the commas. That's 10 characters. attempting to parse an 11 character string to an int would result in a number that is beyond the Int's max value, hence, the NumberFormatException.