Splitting line from a file and storing as separate array values - java

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;
}

Related

Can someone help me figure out what is wrong with my WhiteSpaceCounter code?

I need a program that counts the whitespace in a text document, but it keeps giving me an insane number of whitespaces, as I think the while loop just keeps repeating. could anyone read it over and tell me what is up?
import java.io.*;
public class WhiteSpaceCounter {
public static void main(String[] args) throws IOException {
File file = new File("excerpt.txt");
FileInputStream fis = new FileInputStream(file);
InputStreamReader inreader = new InputStreamReader(fis);
BufferedReader reader = new BufferedReader(inreader);
String sentence;
int countWords = 0, whitespaceCount = 0;
while((sentence = reader.readLine()) != null) {
String[] wordlist = sentence.split("\\s+");
countWords += wordlist.length;
whitespaceCount += countWords -1;
}
System.out.println("The total number of whitespaces in the file is: "
+ whitespaceCount);
}
}
You could also use this
while((sentence = reader.readLine()) != null) {
String[] wordlist = sentence.split("\\s+");
whitespaceCount += wordlist.length-1;
}
If you first line has 3 word and your second line has 10 words, then you logic is
countWords (0) += 3 -> 3
countWords(3) += 10 -> 13
So do not use +=
countWords = wordlist.length;

Split string in Txt files

Lets assume I have a txt file called "Keys.txt":
Keys.txt:
Test 1
Test1 2
Test3 3
I want to split the strings into an array and I dont know how to do it
I want that the result will be
in array like this:
Test
1
Test1
2
Test2
3
I have this started code:
FileReader fr = new FileReader("Keys.txt");
BufferedReader br = new BufferedReader(fr);
String str = br.readLine();
br.close();
System.out.println(str);
You could store all the lines on a single string, separated by spaces, and then split it into your desired array.
FileReader fr = new FileReader("Keys.txt");
BufferedReader br = new BufferedReader(fr);
String str="", l="";
while((l=br.readLine())!=null) { //read lines until EOF
str += " " + l;
}
br.close();
System.out.println(str); // str would be like " Text 1 Text 2 Text 3"
String[] array = str.trim().split(" "); //splits by whitespace, omiting
// the first one (trimming it) to not have an empty string member
You can follow these steps :
read the current line in a String, then split the String on the whitespace (one or more) and you have an array which you can store elements in a List.
repeat the operation for each line.
convert the List to an array(List.toArray()).
For example :
List<String> list = new ArrayList<>();
try (BufferedReader br = new BufferedReader(new FileReader("Keys.txt"))) {
String str;
while ((str = br.readLine()) != null) {
String[] token = str.split("\\s+");
list.add(token[0]);
list.add(token[1]);
}
}
String[] array = list.toArray(new String[list.size()]);
Note that by using Java 8 streams and the java.nio API (available from Java 7) you could be more concise :
String[] array = Files.lines(Paths.get("Keys.txt"))
.flatMap(s -> Arrays.stream(s.split("\\s+"))
.collect(Collectors.toList())
.stream())
.toArray(s -> new String[s]);
String str = "Test 1 Test1 2 Test2 3";
String[] splited = str.split("\\s+");
You can use String.split() method (in your case it's str.split("\\s+");).
It will split input string on one or more whitespace characters. As Java API documentation states here:
\s - A whitespace character: [ \t\n\x0B\f\r]
X+ - X, one or more times.
FileReader fr;
String temp = null;
List<String> wordsList = new ArrayList<>();
try {
fr = new FileReader("D://Keys.txt");
BufferedReader br = new BufferedReader(fr);
while ((temp = br.readLine()) != null) {
String[] words = temp.split("\\s+");
for (int i = 0; i < words.length; i++) {
wordsList.add(words[i]);
System.out.println(words[i]);
}
}
String[] words = wordsList.toArray(new String[wordsList.size()]);
br.close();
} catch (Exception e) {
e.printStackTrace();
}
try this out

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

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]);
}

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...

Benford's Law Java - Extracting first digit from a string array read from a file?

I am trying to create a program in Java that reads from a file, extracts the first digit of every number, determines the frequencies of 0-9, and prints out the frequencies (in percentages) of the numbers 0 through 9. I already figured out how to read from my file ("lakes.txt");
FileReader fr = new FileReader ("lakes.txt");
BufferedReader br = new BufferedReader(fr);
//for loop that traverses each line of the file
int count = 0;
for (String s = br.readLine(); s!= null; s = br.readLine()) {
System.out.println(s); //print out every term
count++;
}
String [] nums;
nums = new String[count];
//close and reset file readers
fr.close();
fr = new FileReader ("lakes.txt");
br = new BufferedReader(fr);
//read each line of the file
count = 0;
for (String s = br.readLine(); s!= null; s = br.readLine()) {
nums[count] = s;
count++;
}
I am currently printing out every term just to make sure it is working.
Now I am trying to figure out how to extract the first digit from each term in my string array.
For example, the first number in the array is 15,917, and I want to extract 1. The second number is 8,090 and I want to extract 8.
How can I do this?
To extract the first number from a String
Get the first letter from the String
Parse (1) into a number
For example:
String firstLetter = Character.toString(s.charAt(0));//alternatively use s.substring(0,1)
int value = Integer.parseInt(firstLetter);
This would be placed inside the file reading loop, assuming each line of the file contains a numeric value (in other words, no further processing or error handling of the lines of the file is required).
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class TermReader {
public static void main(String[] args) throws IOException {
FileReader fr = new FileReader ("lakes.txt");
BufferedReader br = new BufferedReader(fr);
int[] tally = new int[]{0,0,0,0,0,0,0,0,0,0};
int total = 0;
for (String s = br.readLine(); s!= null; s = br.readLine()) {
char[] digits = s.toCharArray();
for(char digit : digits) {
if( Character.isDigit(digit)) {
total++;
tally[Integer.parseInt(Character.toString(digit))]++;
break;
}
}
}
br.close();
for(int index = 0; index < 10; index++) {
double average = tally[index] == 0 ? 0.0 : (((double)tally[index]) / total) * 100;
System.out.println("[" + index + "][" + tally[index] + "][" + total + "][" + Math.round(average * 100.0) / 100.0 + "]");
}
}
}

Categories

Resources