Converting numbers in a string array to a two dimensional int array - java

I am taking data in from a text file with the following information:
Jessica 80 90
Peter 106 50
Lucas 20 85
Sarah 90 40
John 35 12
This data is then being converted into a String array and being outputted by my code. I would like to be able to keep the Names in my string array while converting the numbers into an Array of int[][] so that I can manipulate the variables to find averages for students and the exam. My working code is as follows below:
import java.io.*;
import java.util.*;
public class Array_2D{
public static String[] readLines(String filename) throws IOException {
FileReader fileReader = new FileReader(filename);
BufferedReader bufferedReader = new BufferedReader(fileReader);
List<String> lines = new ArrayList<String>();
String line = null;
while ((line = bufferedReader.readLine()) != null) {
lines.add(line);
}
bufferedReader.close();
return lines.toArray(new String[lines.size()]);
}
public static void inputstream() throws IOException {
String filename = "data.txt";
try {
String[] lines = readLines(filename);
for (String line : lines)
{
System.out.println(line);
}
} catch(IOException e) {
System.out.println("Unable to create " + filename+ ": " + e.getMessage());
}
Does anyone have any information that would help me convert the numbers from the string array to the int[][] so that I may manipulate the numbers by column and row? Thank you for your time.

In your code each line contains one name and two integer,
this may not be generic but try something like that,
String names = new String[numberOfLines];
int scores[][] = new int[numberofLines][2];
for(int i = 0;i < numberOfLines;i ++){
String words[] = lines[i].split("\\s+");
names[i] = words[0];
scores[i][0] = Integer.parseInt(words[1]);
scores[i][1] = Integer.parseInt(words[2]);
}

Related

Compare user string input to a string from a textfile

I'm trying to do a simple login from a textfile. I've used different ways of reading the text from the file to a String line(BufferedReader and Scanner). I am able to get the line into a string, but it doesn't want to compare the 2 strings and match when I use an if statement(.equals()) or even if I use .equalsIgnoreCase(). When I print the 2 strings to be compared they are the same. but my if statement doesn't seem to return true?
This was the last coding i tried (I thought maybe if I put it into an array it would compare true, but still nothing).
Iv'e looked and saw similar questions to comparing strings from textfile, but never saw a problem with the if statement to return true
import java.io.*;
import java.text.*;
import java.lang.*;
public class tes
{
public static void main(String[] args)throws Exception
{
String logline = "JMX^1234";
ArrayList<String> lines = new ArrayList<String>();
FileReader fr = new FileReader("/home/jmx/Desktop/javap/Bank/jm.txt");
BufferedReader br = new BufferedReader(fr);
String rline = br.readLine();
while(rline != null)
{
lines.add(rline);
rline = br.readLine();
}
String[] users = new String[lines.size()];
lines.toArray(users);
for(int i = 0; i < users.length; i++)
{
if(logline.equals(users[i]))
{
System.out.println("Matched");
}
}
System.out.println("Login line: " + logline);
System.out.println("Text Line: " + users[0]);
br.close();
fr.close();
}
}
I've tried to execute your code and everything worked as expected. I received "matched". Maybe it's some kind of encoding issue. Try to compare length and if it is ok, try to leave only one line in the file and try this code:
String logline = "JMX^1234";
ArrayList<String> lines = new ArrayList<String>();
FileReader fr = new FileReader("/home/jmx/Desktop/javap/Bank/jm.txt");
BufferedReader br = new BufferedReader(fr);
String rline = br.readLine();
while(rline != null)
{
lines.add(rline);
rline = br.readLine();
}
String[] users = new String[lines.size()];
lines.toArray(users);
for (char ch : users[0].toCharArray()) {
System.out.print((int)ch);
}
System.out.println();
for (char ch : logline.toCharArray()) {
System.out.print((int)ch);
}
System.out.println();
for(int i = 0; i < users.length; i++)
{
if(logline.equals(users[i]))
{
System.out.println("Matched");
}
}
System.out.println("Login line: " + logline);
System.out.println("Text Line: " + users[0]);
br.close();
fr.close();
It should return equal lines of numbers like this:
7477889449505152
7477889449505152
Matched
Login line: JMX^1234
Text Line: JMX^1234
Also try to check out this answer: https://stackoverflow.com/a/4210732/6226118

How to count the number of characters in a line in a csv file

I have a Justice_League.csv file that has four lines with commas between them. I want to count the number of characters there are in each line and convert that number to hex.
Below is the contents of Justice_League.csv:
Bruce Wayne,Batman,None,Gotham City,Robin,The Joker 43 2B
Oliver Queen,Green Arrow,None,Star City,Speedy,Deathstroke 50 32
Clark Kent,Superman,Flight,Metropolis,None,Lex Luthor 46 2E
Bart Allen,The Flash,Speed,Central City,Kid Flash,Professor Zoom 52 34
As you can see I have handcounted the characters and wrote the HEX value next to it. Now I need this done in Java. This is what I have so far. Can anybody help me out?
public String convertCSVToFlat (Exchange exchange) throws Exception {
String csv="Justice_League.csv";
BufferedReader bReader = new BufferedReader(new FileReader(csv));
String line = "";
int count = 0;
String str[] = new String[200];
int[] a = new int[24];
String[] hexNumber = new String[4];
try {
bReader.readLine();
int characterSum = 0;
int i = 0;
while((line = bReader.readLine()) != null) {
String[] f=line.split(",");
a[count]=Integer.parseInt(f[2]);
str[count]=f[1];
count++;
characterSum += line.length();
hexNumber[i] = Integer.toHexString(characterSum);
i++;
}
} catch (IOException e) {
e.printStackTrace();
}
bReader.close();
return hexNumber.toString();
I suggest you to read the javadoc of String.split. I think that you misunderstood the concept when you did this:
String[] f=line.split(",");
a[count]=Integer.parseInt(f[2]); //--> java.lang.NumberFormatException here!
Avoid using 'magic' numbers in your code like int[] a = new int[24];. Why 24?
Well, here comes a version that do what you want to do. Maybe it isn't the best way to do this but it works.
public void convertCSVToFlat () throws Exception {
String csv="Justice_League.csv";
BufferedReader bReader = new BufferedReader(new FileReader(csv));
//We're storing the values at this 3 arraylists,
//but a better approach is using an object to hold'em
ArrayList<String> lines = new ArrayList<String>();
ArrayList<Integer> chars = new ArrayList<Integer>();
ArrayList<String> hex = new ArrayList<String>();
String line = "";
try {
while((line = bReader.readLine()) != null) {
lines.add(line);
//I'm assuming that you don't want to count the commas and spaces.
//If you want to, comment the next line
line = line.replaceAll(",", "").replaceAll(" ", "");
int c = line.length(); //count remaining chars...
chars.add(c);
hex.add(Integer.toHexString(c));
}
} catch (IOException e) {
e.printStackTrace();
}
bReader.close();
//Just to show the results
for (int i = 0; i < lines.size(); i++) {
System.out.print(lines.get(i));
System.out.print("\t" + chars.get(i));
System.out.println("\t" + hex.get(i));
}
}
Like I said previously, this is a way to solve this. You should try another options to solve this in order to improve your knowledge...

How to merge data from two text file

I have two related text files shown for example in data1.txt and data2.txt. I want to merge the two files to create result.txt. Any idea how to go about this?
data1.txt
books, 3
Shelf, 5
groceries,6
books, 1
Shelf, 2
data2.txt
books,2
shelf,3
groceries,1
result.txt
books, 3, 2
Shelf, 5,3
groceries,6,1
books, 1,2
Shelf, 2, 3
this is a example for you.first you need to add values to 2d list from data2 text file.and then when line is null in file2 you can get mapping value relative to it's text from that list .so i have a method which will return back the mapping value for a String .code is little long than i thought .i post only relevant methods here.This is link to complete class file
public void marged(){
try {
BufferedReader br1 = null;
BufferedReader br2 = null;
String line1;
String line2;
ArrayList<ArrayList<String>> arrayList = new ArrayList<>();
br1 = new BufferedReader(new FileReader("C:\\Users\\Madhawa.se\\Desktop\\workingfox\\data1.txt"));
br2 = new BufferedReader(new FileReader("C:\\Users\\Madhawa.se\\Desktop\\workingfox\\data2.txt"));
while ((line1 = br1.readLine()) != null) {
String[] split1 = line1.split(",");
String line1word = split1[0].trim();
String line1val = split1[1].trim();
line2 = br2.readLine();
if (line2 != null) {
String[] split2 = line2.trim().split(",");
String line2word = split2[0].trim();
String line2val = split2[1].trim();
ArrayList<String> list = new ArrayList();
list.add(line2word);
list.add(line2val);
arrayList.add(list);
if (line1word.equalsIgnoreCase(line2word)) {
String ok = line1word + "," + line1val + "," + line2val;
System.out.println(ok);
}
} else {
String ok = line1word + "," + line1val + "," + doesexist(arrayList, line1word);
System.out.println(ok);
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
this is the method return mapping value
public String doesexist(ArrayList<ArrayList<String>> arrayList, String s) {
for (int i = 0; i < arrayList.size(); i++) {
String get = arrayList.get(i).get(0);
if (get.trim().equalsIgnoreCase(s.trim())) {
return arrayList.get(i).get(1);
}
}
return "-1";
}
output>>
books,3,2
Shelf,5,3
groceries,6,1
books,1,2
Shelf,2,3
Simply add files into an array of File object then read it using loop.
File []files = new Files[amountOfFiles];
//initialize array elements
for(File f:files)
{
//read each file and store it into string variable
}
//finally write the string variable into result.txt file.
import java.io.FileReader;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.FileNotFoundException;
public class SOQ21
{
public SOQ21()
{
merge();
}
public void merge()
{
try
{
String firstfile = "data1.txt";
FileReader fr1 = new FileReader(firstfile);
BufferedReader bfr1 = new BufferedReader(fr1);
String secondfile = "data2.txt";
FileReader fr2 = new FileReader(secondfile);
BufferedReader bfr2 = new BufferedReader(fr2);
/*
^^^ Right here is how you get the files and accompanying BufferedReaders
to handle them
*/
//next, using the readLine() method from the Java API, read each line
//for the first file
//then, separate by taking the words into an ArrayList and storing the
//numbers as Strings in a String[] of equal length of the ArrayList
//Do the same for the second file
//Then, if the word of ArrayList 1 matches the word of ArrayList 2,
//append the String numbers from String[] 2 to String[] 1
//DONE! :)
}
catch(FileNotFoundException ex)
{
//handle how you want
}
}
public static void main(String[] args)
{
SOQ21 soq = new SOQ21();
}
}
The comments I made should answer most of your questions. Lastly, I would pay special attention to the exceptions, I'm not entirely sure how you wanted to deal with that, but make sure you fill it with SOMETHING!

Splitting line from a file and storing as separate array values

I have a requirement where in I need to read contents of a file, each line needs to be read into an array and split the line and store the values into separate variables for further processing.
Sample data from the file
175 31 4 877108051
62 827 2 879373421
138 100 5 879022956
252 9 5 891456797
59 421 5 888206015
Expected output
arr[1][1] = 175
arr[1][2] = 31
arr[1][3] = 2
arr[1][4] = 879373421
arr[2][1] = 62
arr[2][2] = 827
arr[2][3] = 4
arr[2][4] = 877108051
.
.
.
Im able to split properly using StringTokenizer but unable to access individual elements after tokens are formed. Tried with Array.split(), but its not splitting the values into separate array values. Please help me out. Thanks in advance.
My code
static public void main(String[] args) {
File file = new File("small.txt");
String[] lines = new String[100];
FileReader reader = new FileReader(file);
BufferedReader buffReader = new BufferedReader(reader);
int x = 0;
String s;
while((s = buffReader.readLine()) != null){
lines[x] = s;
// Using StringTokenizer
StringTokenizer st = new StringTokenizer(lines[x]);
while (st.hasMoreTokens()){
System.out.println("Next token:"+st.nextToken());
}
// Using Split()
String[] split1 = lines[x].split(" ");
int size = split1.length;
System.out.println("Split size:"+size);
int i = 0;
for (String value : split1) {
System.out.println("Index:"+i+" "+ value); i++;}
}
You can simplify this code a lot.
Try something like this.
1) Read the file line by line, split lines as you go,
add values to some ArrayList containing String[]
2) Close your file
3) Turn the ArrayList into a String[][]
4) Print the result
Also, note that arrays in Java are indexed starting at 0 not at 1.
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.Arrays;
public class Test021 {
static public void main(String[] args) throws Exception {
File file = new File("small.txt");
FileReader reader = new FileReader(file);
BufferedReader buffReader = new BufferedReader(reader);
String s = null;
ArrayList<String[]> lst = new ArrayList<String[]>();
String[][] res = null;
while((s = buffReader.readLine()) != null){
String[] arr = s.split("[\\s]+");
lst.add(arr);
}
buffReader.close();
res = new String[lst.size()][lst.get(0).length];
res = lst.toArray(res);
System.out.println();
// System.out.println(res);
// String result = Arrays.deepToString(res);
// System.out.println(result);
System.out.println();
for (int i=0; i<res.length; i++){
for (int j=0; j<res[i].length; j++){
System.out.println("res[" + (i+1) + "][" + (j+1) + "]=" + res[i][j]);
}
}
System.out.println();
}
}
OUTPUT:
res[1][1]=175
res[1][2]=31
res[1][3]=4
res[1][4]=877108051
res[2][1]=62
res[2][2]=827
res[2][3]=2
res[2][4]=879373421
res[3][1]=138
res[3][2]=100
res[3][3]=5
res[3][4]=879022956
res[4][1]=252
res[4][2]=9
res[4][3]=5
res[4][4]=891456797
res[5][1]=59
res[5][2]=421
res[5][3]=5
res[5][4]=888206015
This might not be the cause, but do not split by space. You may have tabs or LF characters, and/or leading and trailing spaces.
That is, do not use lines[x].split(" ");
split using regex.
lines[x].split("[\\s]+"); //one or more spaces.
Try this code
List<String> lines=new ArrayList<>();
Read file and add line to lines array
File file = new File("data.txt");
FileReader reader = new FileReader(file);
BufferedReader buffReader = new BufferedReader(reader);
String line = buffReader.readLine();
while(line!=null){
lines.add(line);
line = buffReader.readLine();
}
Convert lines array to string 2d array
String string[][]=new String[lines.size()][0];
for(int i=0;i<lines.size();i++){
String s[]=lines.get(i).split(" ");
string[i]=s;
}

How to read a file and store it in array in java

I want to read a text file and store it as string multidimensional array in java.
The input will be like this
11 12 13
12 11 16
33 45 6
I want to store this in
String[][] as={{"11","12","13"},
{"12","11","16"},
{"33","45"}};
My code
String file="e:\\s.txt";
try
{
int counterCol=0,counterRow=0;
String[][] d=null;
BufferedReader bw=new BufferedReader(new FileReader(file));
String str=bw.readLine();
String[] words=str.split(",");
System.out.println(words.length+"Counterrow");
counterCol=words.length; //get total words split by comma : column
while(bw.readLine()!=null)
{
counterRow++;
// to get the total words as it gives total row count
}
String[][] d=new String[counterRow][counterCol];
for(int x=0;x<counterRow;x++)
{
for(int y=0;y<counterCol;y++)
{
d[x][y]=bw.readLine();
//storing in array. But here gives me the exception
}
}
But I cannot store it in array as I getting null pointer exception. How to over come this problem
Quite a few things wrong here:
Array not initialized
You are not looping over the file lines using the BufferedReader
You are splitting by comma instead of space as specified in your sample data
Using Java Collections will help you here. Specifically ArrayList.
Give something like this a go:
String file="e:\\s.txt";
try {
int counterRow = 0;
String[][] d = new String[1][1];
BufferedReader bw = new BufferedReader(new FileReader(file));
List<List<String>> stringListList = new ArrayList<List<String>>();
String currentLine;
while ((currentLine = bw.readLine()) != null) {
if (currentLine != null) {
String[] words = currentLine.split(" ");
stringListList.add(Arrays.asList(words));
}
}
// Now convert stringListList into your array if needed
d = Arrays.copyOf(d, stringListList.size());
for (List<String> stringList : stringListList) {
String[] newArray = new String[stringList.size()];
for (int i = 0; i < stringList.size(); i++) {
newArray[i] = stringList.get(i);
}
d[counterRow] = newArray;
counterRow ++;
}
} catch (Exception e) {
// Handle exception
}
You get NullPointer because your array 'd' is null:
String[][] d=null;
Initialize it and it should be work:
String[][] d= new String [counterCol][counterRow];

Categories

Resources