How to read from File into 2d char Array - java

I'm trying to figure out how to read from a txt which looks like this:
12
12
WWWWWWWWWWWW
W3000000000W
W0000000000W
W0000000000W
W0000000000W
W0000000000W
W0000000040W
W0000000000W
W0000000000W
W0000000000W
W0000000000W
WWWWWWWWWWWW
Into a String[][];
The first 2 lines are the size of the String[][].
This is the code which says
Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: 1 at map[i][j] = temp[j].toString();
public String[][] read() throws IOException{
BufferedReader br = new BufferedReader(new FileReader("D:/College/Java Eclipse/Map.txt"));
String line = " ";
int columnCount = Integer.parseInt(br.readLine());
int rowCount = Integer.parseInt(br.readLine());
String[] temp;
String[][] map = new String[rowCount][columnCount];
while ((line = br.readLine())!= null){
temp = line.split("\\s+");
for(int i = 0; i<rowCount; i++) {
for (int j = 0; j<columnCount; j++) {
map[i][j] = temp[j].toString();
}
}
}
br.close();
return map;
}
What is wrong i can't figure out?

Your regex line.split("\\s+") is returning a single String and you are looping like it is returning an array (in your case) of 12 elements; and anyway you are replacing all your values again and again because you are reading outside the first for loop.
Try something like this instead:
public static String[][] read() throws IOException {
BufferedReader br = new BufferedReader(new FileReader("D:/College/Java Eclipse/Map.txt"));
int columnCount = Integer.parseInt(br.readLine());
int rowCount = Integer.parseInt(br.readLine());
String[][] map = new String[rowCount][columnCount];
for (int i = 0; i < rowCount; i++) {
String line = br.readLine();
for (int j = 0; j < columnCount; j++) {
map[i][j] = String.valueOf(line.charAt(j));
}
}
br.close();
//System.out.println(Arrays.deepToString(map));
return map;
}

Related

How to take multiple inputs in java in a single line

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int num = Integer.parseInt(br.readLine()); //Length of Array
int t = num * 2;
String s;
for(int i = 0; i<num; i++) {
s = br.readLine();
}
int[] arr= new int[t];
String[] s1 = s.split(" ");
for(int i=0;i<num;i++)
{
arr[i]=Integer.parseInt(s1[i]);
}
for(int j = 0; j< arr.length; j++) {
System.out.println(arr[j]);
}
Here i have attempted to taken a value in variable num and i want to take input the number of times in a single line according to variable num but if i am printing the arr i am getting only two values which i have given the input in last rest are 0. I think s is replaced with the new input i have entered please help me to solve this
You can add string like this:
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int num = Integer.parseInt(br.readLine()); // Length of Array
String s = "";
for (int i = 0; i < num; i++) {
s += br.readLine() + " ";
}
int[] arr = new int[num * 2];
String[] s1 = s.split("[\\s]");
for (int i = 0; i < s1.length; i++) {
arr[i] = Integer.parseInt(s1[i]);
}
System.out.println(Arrays.toString(arr));
}
, output
2
1 2
3 4
[1, 2, 3, 4]
You can try this:
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int num = 0; //Length of Array
try {
num = Integer.parseInt(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
int t = num * 2;
int[] arr= new int[t];
String s;
for(int i = 0, j = 0; i<num; i++) {
try {
s = br.readLine();
String[] s1 = s.split(" ");
arr[j++] = Integer.parseInt(s1[0]);
arr[j++] = Integer.parseInt(s1[1]);
} catch (IOException e) {
e.printStackTrace();
}
}
for(int j = 0; j< arr.length; j++) {
System.out.println(arr[j]);
}
You can use Scanner Class to directly take the input as integer.
import java.util.Scanner;
public class prac {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner in = new Scanner(System.in);
int num, i;
num = in.nextInt();
int ar[][] = new int[num][2];
for (i = 0; i < num; i++) {
ar[i][0] = in.nextInt();
ar[i][1] = in.nextInt();
}
for (i = 0; i < num; i++) {
System.out.println(ar[i][0] + " " + ar[i][1]);
}
}
}
OUTPUT :
2
1 5
6 8
1 5 //This is the Output
6 8
The above code is storing input in 2D array. You could store the same in 1D array also.

CSV Handling / FileReader and BufferedReader with UTF-8

I am having issues with reading a csv file and UTF-8. What I am doing is, reading the file to a String Array. Converting the String Array to a 2D String Array, depending on the line separator. Cleaning the line separator and displaying the 2D String Array in the console.
The issue is, that special characters like ö and ä are messed up on the console.
System.out.println("Default Charset=" + Charset.defaultCharset());
Tells me that my system is using UTF-8. What am I doing wrong?
I´m handling the CSV files with a 2D Array to get direct access to the rows and columns. Is there a better approach for that?
// Reading File
public static String[] readFile(String path) throws IOException {
FileReader input = new FileReader(path);
BufferedReader br = new BufferedReader(input);
String[] stringBuff = new String[countLines(path)];
int lines = countLines(path);
for (int j = 0; j < lines; j++) {
stringBuff[j] = br.readLine();
}
br.close();
return stringBuff;
}
// Converting to a 2D Array
public static String[][] convert(String[] array, String path) throws IOException {
int lines = countLines(path);
int[] locationarray;
int columns = (findcolumn(array)) + 1;
String[][] array2 = new String[lines][columns];
for (int i = 0; i < array.length; i++) {
locationarray = findlocation(array, i);
for (int j = 0; j < columns; j++) {
array2[i][j] = array[i].substring(locationarray[j], locationarray[j + 1]);
array2[i][j] = cleanup(array2[i][j]);
// System.out.print(array2[i][j]);
}
// System.out.println();
}
return array2;
}
// Show Array
public static void showarray(String[][] srcfinal) {
for (int i = 0; i < srcfinal.length; i++) {
for (int j = 0; j < srcfinal[i].length; j++) {
System.out.print(srcfinal[i][j]);
}
System.out.println();
}
}

How do you convert a text file into a 2D character array?

I am trying to convert a text file into a 2 dimensional character array. I am part of the way there but the last line of my array is not fully correct. Here's my code:
protected void readMap(String fileName) throws IOException {
BufferedReader br = new BufferedReader(new FileReader(fileName));
char[] chars;
int lines=0;
while (br.readLine() != null) {
lines++;
}
File file = new File(fileName);
try (FileReader reader = new FileReader(file)) {
chars = new char[(int) file.length()];
reader.read(chars);
reader.close();
} catch (IOException e) {
}
int columns = ((int) file.length())/lines;
map = new char[lines][columns];
for(int i=0; i<lines;i++){
for(int j=0;j<columns;j++){
map[i][j] = chars[j%columns+i*columns];
}
}
for(int ro=0; ro<map.length; ro++){
for(int colum=0; colum<(map[0].length); colum++){
System.out.print(map[ro][colum]);
}
}
return null;
}
Here's the output:
##########################
#........................#
#.....###........###.....#
#......G..........G......#
#........................#
#...........E............#
#......G.........G.......#
#........G.....G.........#
#..........###...........#
#........................#
#################
^missing #'s here
I'm very confused on why this is occuring. I've tried changing how I print the array but i'm pretty sure its how its to do with how i've converted the 1d 'chars' array to the 2d 'map' array.
I'm really lost so any help would be much appreciated! Thank you.
I'm guessing your file looks something like this
##########################
#........................#
#.....###........###.....#
#......G..........G......#
#........................#
#...........E............#
#......G.........G.......#
#........G.....G.........#
#..........###...........#
#........................#
##########################
If you print the file length, you will see that the file length is 296
As Your code row = 11 and columns = 26
When you are copying to map you are copying up to 11 * 26 = 286
Try the UPDATED code below
public void readMap(String fileName) throws IOException {
BufferedReader br = new BufferedReader(new FileReader(fileName));
int lines = 0, columns = 0;
String str;
List<String> lineList = new ArrayList<>();
while ((str = br.readLine()) != null && str.length() != 0) {
lines++;
columns = Math.max(columns, str.length()); // as it's not fixed
lineList.add(str);
}
System.out.println("Row : " + lines);
System.out.println("Columns : " + columns);
char[][] map = new char[lines][columns];
for (int i = 0; i < lines; i++) {
String currentLine = lineList.get(i);
int idx = 0;
for (int j = 0; j < currentLine.length(); j++) {
map[i][j] = currentLine.charAt(idx++);
}
}
for (int r = 0; r < map.length; r++) {
for (int c = 0; c < (map[0].length); c++) {
System.out.print(map[r][c]);
}
System.out.println();
}
}
I've just executed the code and the map prints as expected. The issue may be down to the file itself as that is the uncommon factor.
edit:
The results you have observed is because you may have a new line character, or other special character, at the end of or somewhere in the file. Removing this you should see the consistent map you want.
Alternative
protected static void readMap(String fileName) throws IOException {
BufferedReader br = new BufferedReader(new FileReader(fileName));
String line = "";
List<String> lines = new ArrayList<>();
while ((line = br.readLine()) != null) {
lines.add(line);
}
char[][] chars = new char[lines.size()][];
for (int col = 0; col < lines.size(); col++) {
for (int row = 0; row < lines.get(col).length(); row++) {
chars[col] = lines.get(col).toCharArray();
}
}
for (int col = 0; col < chars.length; col++) {
for (int row = 0; row < chars[col].length; row++) {
System.out.print(chars[col][row]);
}
System.out.println();
}
}//My rows and cols may be back to front
Few other notes:
You shouldn't be returning a value from a void method, even null (You'll want to return null if the return type is Void).
Your compiler may complain if you don't initialize chars initially, as mine did. char[] chars = null; would do it in this scenario.

Read .txt file and store in 2-D char array java

I am kind of stuck. How do I get this to work or are there a better way? Please give code examples.
public char[][] charmap = new char[SomeInts.amount][SomeInts.amount];
public void loadMap() throws IOException{
BufferedReader in = new BufferedReader(new FileReader("map1.txt"));
String line = in.readLine();
while (line != null){
int y = 0;
for (int x = 0; x < line.length(); x++){
//Error
charmap[x][y] = line[x];
//
}
y++;
}
}
The syntax line[x] is reserved for arrays. A String is not an array. You could use the String#charAt method and write:
charmap[x][y] = line.charAt(x);
Use String.charAt(int) to fetch character from strings..
Try this.
char[][] mapdata = new char[SomeInts.amount][SomeInts.amount];
public void loadMap() throws IOException{
BufferedReader in = new BufferedReader(new FileReader("map1.txt"));
String line = in.readLine();
ArrayList<String> lines = new ArrayList<String>();
// Load all the lines
while (line != null){
lines.add(line);
}
// Parse the data
for (int i = 0; i < lines.size(); i++) {
for (int j = 0; j < lines.get(i).length(); j++) {
mapdata[j][i] = lines.get(i).charAt(j);
}
}
}
Hope this helps.

read file, convert string to double, store in 2d array

I need to read a list of numbers in a file and store it into a 2d array.
This is what I have so far. How would I go about achieving this goal?
//this is only part of my code
public class RainFall
{
double[][] precip;
public RainFall()
{
precip = new double [5][12];
}
public void readFile(BufferedReader infile) throws IOException
{
FileInputStream infile = new FileInputStream("numbers.dat");
BufferedReader br = new BufferedReader(new InputStreamReader(infile));
String[][] myarray = new String[5][12];
while (infile.readLine() != null)
{
for (int j = 0; j < 5; j++)
{
for (int i = 0; i < 12; i++)
{
myarray[j][i] = infile.readLine();
}
}
}
infile.close();
}
numbers.dat is 60 lines of:
1.01
0.03
2.14
0.47
//Is each number on a new line? You're very close, I added a few lines below.
public class RainFall
{
double[][] precip;
public RainFall()
{
precip = new double [5][12];
}
public void readFile(BufferedReader infile) throws IOException
{
//FileInputStream infile = new FileInputStream("numbers.dat");
BufferedReader br = new BufferedReader(new FileReader("numbers.dat"));
String line = "";
String[][] myarray = new String[5][12];
while ((line = br.readLine()) != null)
{
double num = Double.parseDouble(line.trim());
for (int j = 0; j < 5; j++)
{
for (int i = 0; i < 12; i++)
{
precip[j][i] = num;
}
}
}
br.close();
}
Instead of
String[][] myarray = new String[5][12];
use
double[][] myarray = new double[5][12];
Then sub this into the loop:
myarray[j][i] = Double.parseDouble(infile.readLine());

Categories