Adding multiple arraylist integers together - java

UPDATED:
After making the changes using Mike Kobit's answer, i wanted to move the files that i have already calculated to a different folder. the files do not successfully move and i dont know why? Does it have to do with the array list locking the files?
public static void main(String[] args) throws FileNotFoundException {
fSplit(path);
Date date = new Date();
SimpleDateFormat d = new SimpleDateFormat("yyyyMMdd_HHmmSS");
String d_f = d.format(date);
System.out.println(allSums);
try {
File fold = new File(path);
for(File k : fold.listFiles()) {
System.out.println(k.getName());
if(k.getName().contains("file")) { //named files read to be moved
boolean success = k.renameTo(new File(path2 + "\\" + k.getName()));
if(!success) {
System.out.println("FAILED MOVE");
}
}
}
} catch(Exception e) { e.printStackTrace(); }
}
private static void fSplit(String path) throws FileNotFoundException {
//ArrayList<Integer> allSums = new ArrayList<>();
//ArrayList<List<Integer>> allLists = new ArrayList<>();
File folder = new File(path);
for (File f : folder.listFiles()) {
//System.out.println(f.getName());
BufferedReader br = new BufferedReader(new FileReader(path + "\\" + f.getName()));
Scanner scanner = new Scanner(br);
ArrayList<Integer> list = new ArrayList<Integer>();
while(scanner.hasNext()) {
list.add(scanner.nextInt());
}
// Store each read list into a container for all of the lists
allLists.add(list);
//System.out.println(list);
}
// Assuming all lists are the same size
//int listLength = allLists.get(0).size();
// Iterate over each index
for(int i = 0; i < 5; i++) {
int sum = 0;
// For each index, add the elements from that index in each list
for(List<Integer> list : allLists) {
sum += list.get(i);
}
// Add the current indexes sum to the final list
allSums.add(sum);
}
}

You need to keep track of your arrays and then you can iterate over them. Here is your example with added comments and how you could sum up the elements after.
ArrayList<Integer> allSums = new ArrayList<>();
ArrayList<List<Integer>> allLists = new ArrayList<>();
for (File f : folder.listFiles()) {
BufferedReader br = new BufferedReader(new FileReader(path + "\\" + f.getName()));
Scanner scanner = new Scanner(br);
ArrayList<Integer> list = new ArrayList<Integer>();
while (scanner.hasNext()) {
list.add(scanner.nextInt());
}
// Store each read list into a container for all of the lists
allLists.add(list);
System.out.println(list);
}
// Assuming all lists are the same size
final int listLength = allLists.get(0).size();
// Iterate over each index
for (int i = 0; i < listLength; i++) {
int sum = 0;
// For each index, add the element from that index in each list
for (List<Integer> list : allLists) {
sum += list.get(i);
}
// Add the current indexes sum to the final list
allSums.add(sum);
}
// allSums contains the sum from every index
// Using Java 8 streams
allSums.clear();
IntStream.range(0, listLength)
.forEach((i) -> allSums.add(i, allLists.stream().collect(Collectors.summingInt((c) -> c.get(i)))));
System.out.println(allSums);
Output from both ways:
[11, 12, 6, 5, 11]
[11, 12, 6, 5, 11]

If you want to add using ArrayList you can do this
List<Integer> sum = new ArrayList<Integer>(5);
for (int i = 0; i < sum.size(); i++) {
sum.add(i, list1.get(i) + list2.get(i) + list3.get(i));
}

Explantion:In the for loop you will add all same index elements in different array with each other and save it in same index at result array
Note:
my code is done with array but I am sure you can change it to arraylist very easily
Code:
List<Integer> list1 = Arrays.asList(5, 4, 3, 1, 0);
List<Integer> list2 = Arrays.asList(3, 4, 2, 1, 5);
List<Integer> list3 = Arrays.asList(3, 4, 1, 3, 6);
List<Integer> result = new ArrayList<>();
// you cannot use reslut size because result does not have anything in it, so
// there is no size for result list.
// you can use size each list as long as the size of all the list is the same
for (int i = 0; i < list1.size(); i++) {
result.add(i, list1.get(i) + list2.get(i) + list3.get(i));
}
for (int i = 0; i < result.length; i++) {
System.out.print(result.get(i)+" ");
}
Output:
11 12 6 5 11

Related

Effective way to read file and parse each line

I have a text file of next format: each line starts with a string which is followed by sequence of numbers. Each line has unknown length (unknown amount of numbers, amount from 0 to 1000).
string_1 3 90 12 0 3
string_2 49 0 12 94 13 8 38 1 95 3
.......
string_n 9 43
Afterwards I must handle each line with handleLine method which accept two arguments: string name and numbers set (see code below).
How to read the file and handle each line with handleLine efficiently?
My workaround:
Read file line by line with java8 streams Files.lines. Is it blocking?
Split each line with regexp
Convert each line into header string and set of numbers
I think it's pretty uneffective due 2nd and 3rd steps. 1st step mean that java convert file bytes to string first and then in 2nd and 3rd steps I convert them back to String/Set<Integer>. Does that influence performance a lot? If yes - how to do better?
public handleFile(String filePath) {
try (Stream<String> stream = Files.lines(Paths.get(filePath))) {
stream.forEach(this::indexLine);
} catch (IOException e) {
e.printStackTrace();
}
}
private void handleLine(String line) {
List<String> resultList = this.parse(line);
String string_i = resultList.remove(0);
Set<Integer> numbers = resultList.stream().map(Integer::valueOf).collect(Collectors.toSet());
handleLine(string_i, numbers); // Here is te final computation which must to be done only with string_i & numbers arguments
}
private List<String> parse(String str) {
List<String> output = new LinkedList<String>();
Matcher match = Pattern.compile("[0-9]+|[a-z]+|[A-Z]+").matcher(str);
while (match.find()) {
output.add(match.group());
}
return output;
}
Regarding your first question, it depends on how you reference the Stream. Streams are inherently lazy, and don't do work if you're not going to use it. For example, the call to Files.lines doesn't actually read the file until you add a terminal operation on the Stream.
From the java doc:
Read all lines from a file as a Stream. Unlike readAllLines, this method does not read all lines into a List, but instead populates lazily as the stream is consumed
The forEach(Consumer<T>) call is a terminal operation, and, at that point, the lines of the file are read one by one and passed to your indexLine method.
Regarding your other comments, you don't really have a question here. What are you trying to measure/minmize? Just because something is multiple steps doesn't inherently make it have poor performance. Even if you created a wizbang oneliner to convert from the File bytes directly to your String & Set, you probably just did the intermediate mapping anonymously, or you've called something that will cause the compiler to do that anyway.
Here is your code to parse line into name and numbers
stream.forEach(line -> {
String[] split = line.split("\\b"); //split with blank seperator
Set<String> numbers = IntStream.range(1, split.length)
.mapToObj(index -> split[index])
.filter(str -> str.matches("\\d+")) //filter numbers
.collect(Collectors.toSet());
handleLine(split[0], numbers);
});
Or another way
Map<Boolean, List<String>> collect = Pattern.compile("\\b")
.splitAsStream(line)
.filter(str -> !str.matches("\\b"))
.collect(Collectors.groupingBy(str -> str.matches("\\d+")));
handleLine(collect.get(Boolean.FALSE).get(0), collect.get(Boolean.TRUE));
I set out to test several ways to go about this problem and measure the performance as best I could under noted conditions. Here's what I tested and how I tested it, along with the accompanying results:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Random;
import java.util.Scanner;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.Stream;
public class App {
public static void method1(String testFile) {
List<Integer> nums = null;
try (Scanner s = new Scanner(Paths.get(testFile))) {
while (s.hasNext()) {
if (s.hasNextInt())
nums.add(s.nextInt());
else {
nums = new ArrayList<Integer>();
String pre = s.next();
// handleLine( s.next() ... nums ... );
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
public static void method2(String testFile) {
List<Integer> nums = null;
try (BufferedReader in = new BufferedReader(new FileReader(testFile));
Scanner s = new Scanner(in)) {
while (s.hasNext()) {
if (s.hasNextInt())
nums.add(s.nextInt());
else {
nums = new ArrayList<Integer>();
String pre = s.next();
// handleLine( s.next() ... nums ... );
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
public static void method3(String testFile) {
List<Integer> nums = null;
try (BufferedReader br = new BufferedReader(new FileReader(testFile))) {
String line = null;
while ((line = br.readLine()) != null) {
String[] arr = line.split(" ");
nums = new ArrayList<Integer>();
for (int i = 1; i < arr.length; ++i)
nums.add(Integer.valueOf(arr[i]));
// handleLine( ... );
}
} catch (IOException e) {
e.printStackTrace();
}
}
public static void method3_1(String testFile) {
List<Integer> nums = null;
try (BufferedReader br = new BufferedReader(new FileReader(testFile))) {
String line = null;
while ((line = br.readLine()) != null) {
String[] arr = line.split(" ");
nums = new ArrayList<Integer>();
for (int i = 1; i < arr.length; ++i)
nums.add(Integer.parseInt(arr[i]));
// handleLine( ... );
}
} catch (IOException e) {
e.printStackTrace();
}
}
public static void method4(String testFile) {
List<Integer> nums = null;
try {
List<String> lines = Files.readAllLines(Paths.get(testFile));
for (String s : lines) {
String[] arr = s.split(" ");
nums = new ArrayList<Integer>();
for (int i = 1; i < arr.length; ++i)
nums.add(Integer.valueOf(arr[i]));
// handleLine( ... );
}
} catch (IOException e) {
e.printStackTrace();
}
}
public static void method4_1(String testFile) {
List<Integer> nums = null;
try {
List<String> lines = Files.readAllLines(Paths.get(testFile));
for (String s : lines) {
String[] arr = s.split(" ");
nums = new ArrayList<Integer>();
for (int i = 1; i < arr.length; ++i)
nums.add(Integer.parseInt(arr[i]));
// handleLine( ... );
}
} catch (IOException e) {
e.printStackTrace();
}
}
public static void method5(String testFile) {
List<Integer> nums = null;
try (BufferedReader br = Files.newBufferedReader(Paths.get(testFile))) {
List<String> lines = br.lines().collect(Collectors.toList());
for (String s : lines) {
String[] arr = s.split(" ");
nums = new ArrayList<Integer>();
for (int i = 1; i < arr.length; ++i)
nums.add(Integer.valueOf(arr[i]));
// handleLine( ... );
}
} catch (IOException e) {
e.printStackTrace();
}
}
public static void method5_1(String testFile) {
List<Integer> nums = null;
try (BufferedReader br = Files.newBufferedReader(Paths.get(testFile))) {
List<String> lines = br.lines().collect(Collectors.toList());
for (String s : lines) {
String[] arr = s.split(" ");
nums = new ArrayList<Integer>();
for (int i = 1; i < arr.length; ++i)
nums.add(Integer.parseInt(arr[i]));
// handleLine( ... );
}
} catch (IOException e) {
e.printStackTrace();
}
}
public static void method6(String testFile) {
List<Integer> nums = new LinkedList<Integer>();
try (Stream<String> stream = Files.lines(Paths.get(testFile))) {
stream.forEach(line -> {
String[] split = line.split("\\b"); // split with blank seperator
Set<String> numbers = IntStream.range(1, split.length)
.mapToObj(index -> split[index])
.filter(str -> str.matches("\\d+")) // filter numbers
.collect(Collectors.toSet());
numbers.forEach((k) -> nums.add(Integer.parseInt(k)));
// handleLine( ... );
});
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) throws Exception {
args = new String[] { "C:\\Users\\Nick\\Desktop\\test.txt" };
Random r = new Random();
System.out.println("warming up a little...");
for (int i = 0; i < 100000; ++i) {
int x = r.nextInt();
}
long s1 = System.currentTimeMillis();
for (int i = 0; i < 10000; ++i)
method1(args[0]);
long e1 = System.currentTimeMillis();
long s2 = System.currentTimeMillis();
for (int i = 0; i < 10000; ++i)
method2(args[0]);
long e2 = System.currentTimeMillis();
long s3 = System.currentTimeMillis();
for (int i = 0; i < 10000; ++i)
method3(args[0]);
long e3 = System.currentTimeMillis();
long s3_1 = System.currentTimeMillis();
for (int i = 0; i < 10000; ++i)
method3_1(args[0]);
long e3_1 = System.currentTimeMillis();
long s4 = System.currentTimeMillis();
for (int i = 0; i < 10000; ++i)
method4(args[0]);
long e4 = System.currentTimeMillis();
long s4_1 = System.currentTimeMillis();
for (int i = 0; i < 10000; ++i)
method4_1(args[0]);
long e4_1 = System.currentTimeMillis();
long s5 = System.currentTimeMillis();
for (int i = 0; i < 10000; ++i)
method5(args[0]);
long e5 = System.currentTimeMillis();
long s5_1 = System.currentTimeMillis();
for (int i = 0; i < 10000; ++i)
method5_1(args[0]);
long e5_1 = System.currentTimeMillis();
long s6 = System.currentTimeMillis();
for (int i = 0; i < 10000; ++i)
method6(args[0]);
long e6 = System.currentTimeMillis();
System.out.println("method 1 = " + (e1 - s1) + " ms");
System.out.println("method 2 = " + (e2 - s2) + " ms");
System.out.println("method 3 = " + (e3 - s3) + " ms");
System.out.println("method 3_1 = " + (e3_1 - s3_1) + " ms");
System.out.println("method 4 = " + (e4 - s4) + " ms");
System.out.println("method 4_1 = " + (e4_1 - s4_1) + " ms");
System.out.println("method 5 = " + (e5 - s5) + " ms");
System.out.println("method 5_1 = " + (e5_1 - s5_1) + " ms");
System.out.println("method 6 = " + (e6 - s6) + " ms");
}
}
Used with java.version = 1.8.0_101 (Oracle)
x64 OS/processor
Result output:
warming up a little...
method 1 = 1103 ms
method 2 = 872 ms
method 3 = 440 ms
method 3_1 = 418 ms
method 4 = 413 ms
method 4_1 = 376 ms
method 5 = 439 ms
method 5_1 = 384 ms
method 6 = 646 ms
To my understanding, the best approach out of the sample I tested was using Files.readAllLines, s.split(" "), and Integer.parseInt. Those three combinations produced the apparently fastest again, out of the sample I created and tested with At least maybe you'd change to the Integer.parseInt to help somewhat.
Note I used sources to help gain some sought after approaches and applied them to this problem/example. E.g. this blog post, this tutorial, and this awesome dude #Peter-Lawrey. Also, further improvements can always be made!
Also, the test.txt file:
my_name 15 00 29 101 1234
cool_id 11 00 01 10 010101
longer_id_name 1234
dynamic_er 1 2 3 4 5 6 7 8 9 10 11 12 123 1456 15689 555555555
(note: performance may greatly vary depending on file size!)

insert values into integer array from List of type string

I want the values printed in line 5 to be inserted into an integer array.
The file contains both integer values and String values.
****I am still in learning process****
Sorry i changed the question a bit.
Thank you
File f = new File("SampleInput.txt");
try{
ArrayList<String> lines = get_arraylist_from_file(f);
for(int x =23; x < lines.size(); x++){
System.out.println(lines.get(x));
**enter code here**
}
}
catch(Exception e){
System.out.println("File not found!!!!");
}
}
public static ArrayList<String> get_arraylist_from_file(File f)
throws FileNotFoundException {
Scanner s;
ArrayList<String> list = new ArrayList<String>();
s = new Scanner(f);
while (s.hasNext()) {
list.add(s.next());
}
s.close();
return list;
}
List<Integer> numList = new ArrayList<>();
File f = new File("SampleInput.txt");
try{
ArrayList<String> lines = get_arraylist_from_file(f);
for(int x =23; x < lines.size(); x++){
System.out.println(lines.get(x));
**enter code here**
numList.add(Integer.parseInt(lines.get(x)));
}
}
I'm guessing you want something like this,
try{
ArrayList<String> lines = get_arraylist_from_file(f);
ArrayList<int> intLines = new ArrayList();
for (int x = 23; x < lines.size(); x++) {
System.out.println(lines.get(x));
intLines.add(Integer.parseInt(lines.get(x)));
}
}
Easier to use an ArrayList of Integers as follows
List<Integer> list = new ArrayList<Integer>();
File f = new File("SampleInput.txt");
try{
ArrayList<String> lines = get_arraylist_from_file(f);
for(int x =23; x < lines.size(); x++){
System.out.println(lines.get(x));
list.add(Integer.parseInt(lines.get(x)));
}
}
catch(Exception e){
System.out.println("File not found!!!!");
}
}
You have to create an int array outside of the loop of the appropriate size, and then just parse the strings and add them to the array in the loop:
ArrayList<String> lines = get_arraylist_from_file(f);
int[] intArray = new int[lines.size-23];
for(int x =23; x < lines.size(); x++){
System.out.println(lines.get(x));
//**enter code here**
String line = lines.get(x);
intArray[x-23] = Integer.parseInt(line);
}

List<String[]> method Adding always same values

In my Java Project, i want to read values from txt file to List method.Values seems like;
1 kjhjhhkj 788
4 klkkld3 732
89 jksdsdsd 23
Number of row changable. I have tried this codes and getting same values in all indexes.
What can i do?
String[] dizi = new String[3];
List<String[]> listOfLists = new ArrayList<String[]>();
File f = new File("input.txt");
try {
Scanner s = new Scanner(f);
while (s.hasNextLine()) {
int i = 0;
while (s.hasNext() && i < 3) {
dizi[i] = s.next();
i++;
}
listOfLists.add(dizi);
}
} catch (FileNotFoundException e) {
System.out.println("Dosyaya ba?lanmaya çal???l?rken hata olu?tu");
}
int q = listOfLists.size();
for (int z = 0; z < q; z++) {
for (int k = 0; k < 3; k++) {
System.out.print(listOfLists.get(z)[k] + " ");
}
}
String [] dizi = new String [3];
dizi is a global variable getting overridden eveytime in the loop. Thats why you are getting same values at all indexes
Make a new instance everytime before adding to the list.
You put the same reference to the list, create a new array in while loop.
while (s.hasNextLine()){
String[] dizi = new String[3]; //new array
int i = 0;
while (s.hasNext() && i < 3)
{
dizi[i] = s.next();
i++;
}
listOfLists.add(dizi);
}

Storing Data from File into an Array

So I have a text file with items like look like this:
350279 1 11:54 107.15
350280 3 11:55 81.27
350281 2 11:57 82.11
350282 0 11:58 92.43
350283 3 11:59 86.11
I'm trying to create arrays from those values, in which the first values of each line are in an array, the second values of each line are in an array, and so on.
This is all the code I have right now, and I can't seem to figure out how to do it.
package sales;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Sales {
public static void main (String[] args) throws FileNotFoundException {
Scanner reader = new Scanner(new File("sales.txt"));
int[] transID = new int[reader.nextInt()];
int[] transCode = new int[reader.nextInt()];
String[] time = new String[reader.next()];
double[] trasAmount = new double[reader.hasNextDouble()];
}
}
It's difficult to build an array this way, because Arrays have fixed size... you need to know how many elements they have. If you use a List instead, you don't have to worry about knowing the number of elements in advance. Try this (note: there is no error checking here!):
public static void main (String[] args) throws FileNotFoundException {
Scanner reader = new Scanner(new File("sales.txt"));
List<Integer> ids = new LinkedList<>();
List<Integer> codes = new LinkedList<>();
List<String> times = new LinkedList<>();
List<Double> amounts = new LinkedList<>();
// Load elements into Lists. Note: you can just use the lists if you want
while(reader.hasNext()) {
ids.add(reader.nextInt());
codes.add(reader.nextInt());
times.add(reader.next());
amounts.add(reader.nextDouble());
}
// Create arrays
int[] idArray = new int[ids.size()];
int[] codesArray = new int[codes.size()];
String[] timesArray = new String[times.size()];
double[] amountsArray = new double[amounts.size()];
// Load elements into arrays
int index = 0;
for(Integer i : ids) {
idArray[index++] = i;
}
index = 0;
for(Integer i : codes) {
codesArray[index++] = i;
}
index = 0;
for(String i : times) {
timesArray[index++] = i;
}
index = 0;
for(Double i : ids) {
amountsArray[index++] = i;
}
}
Use Array list because Arrays have fixed size and using Arraylist you add the elements dynamically
Scanner reader = new Scanner(new File("test.txt"));
List<Integer> transID = new ArrayList<Integer>();
List<Integer> transCode = new ArrayList<Integer>();
List<String> time= new ArrayList<String>();
List<Double> trasAmount = new ArrayList<Double>();
while(reader.hasNext() )
{
transID.add(reader.nextInt());
transCode.add(reader.nextInt());
time.add(reader.next());
trasAmount.add(reader.nextDouble());
}
System.out.println(transID.toString());
System.out.println(transCode.toString());
System.out.println(time.toString());
System.out.println(trasAmount.toString());
Output of the above code
transID [350279, 350280, 350281, 350282, 350283]
transCode [1, 3, 2, 0, 3]
time [11:54, 11:55, 11:57, 11:58, 11:59]
trasAmount [107.15, 81.27, 82.11, 92.43, 86.11]
You'll need a while loop to check for input. Since not all inputs are integers you might do something like:
while(reader.hasNextLine()){ //checks to make sure there's still a line to be read in the file
String line=reader.nextLine(); //record that next line
String[] values=line.split(" "); //split on spaces
if(values.length==4){
int val1=Integer.parseInt(values[0]); //parse values
int val2=Integer.parseInt(values[1]);
String val3=values[2];
double val4=Double.parseDouble(values[3]);
//add these values to your arrays. Might have to "count" the number of lines on a first pass and then run through a second time... I've been using the collections framework for too long to remember exactly how to work with arrays in java when you don't know the size right off the bat.
}
}
In addition to my comment here are 3 ways how you cant do it
read into single arrays
int size = 2;
// first allocate some memory for each of your arrays
int[] transID = new int[size];
int[] transCode = new int[size];
String[] time = new String[size];
double[] trasAmount = new double[size];
Scanner reader = new Scanner(new File("sales.txt"));
// keep track of how many elements you have read
int i = 0;
// start reading and continue untill there is no more left to read
while(reader.hasNext()) {
// since array size is fixed and you don't know how many line your file will have
// you have to reallocate your arrays when they have reached their maximum capacity
if(i == size) {
// increase capacity by 5
size += 5;
// reallocate temp arrays
int[] tmp1 = new int[size];
int[] tmp2 = new int[size];
String[] tmp3 = new String[size];
double[] tmp4 = new double[size];
// copy content to new allocated memory
System.arraycopy(transID, 0, tmp1, 0, transID.length);
System.arraycopy(transCode, 0, tmp2, 0, transCode.length);
System.arraycopy(time, 0, tmp3, 0, time.length);
System.arraycopy(trasAmount, 0, tmp4, 0, trasAmount.length);
// reference to the new memory by your old old arrays
transID = tmp1;
transCode = tmp2;
time = tmp3;
trasAmount = tmp4;
}
// read
transID[i] = Integer.parseInt(reader.next());
transCode[i] = Integer.parseInt(reader.next());
time[i] = reader.next();
trasAmount[i] = Double.parseDouble(reader.next());
// increment for next line
i++;
}
reader.close();
for(int j = 0; j < i; j++) {
System.out.println("" + j + ": " + transIDList.get(j) + ", " + transCodeList.get(j) + ", " + timeList.get(j) + ", " + trasAmountList.get(j));
}
as you see this is a lot of code.
Better you use lists so get rid of the overhead of reallocation and copying (at leas in your own code)
read into single lists
// instanciate your lists
List<Integer> transIDList = new ArrayList<>();
List<Integer> transCodeList = new ArrayList<>();
List<String> timeList = new ArrayList<>();
List<Double> trasAmountList = new ArrayList<>();
reader = new Scanner(new File("sales.txt"));
int i = 0;
while(reader.hasNext()) {
// read
transIDList.add(Integer.parseInt(reader.next()));
transCodeList.add(Integer.parseInt(reader.next()));
timeList.add(reader.next());
trasAmountList.add(Double.parseDouble(reader.next()));
i++;
}
reader.close();
for(int j = 0; j < i; j++) {
System.out.println("" + j + ": " + transIDList.get(j) + ", " + transCodeList.get(j) + ", " + timeList.get(j) + ", " + trasAmountList.get(j));
}
You see here how small the code went? But but it still can get better...
A line in the sales.txt file seem to constitute data elements of some entity, why not put them in an object ? for that you may write a class named Trans, some think like this:
class Trans {
public int transID;
public int transCode;
public String time;
public double trasAmount;
#Override
public String toString() {
return transID + ", " + transCode + ", " + time + ", " + trasAmount;
}
}
Then you can use this class to hold the data you read from your file and put each object of that class in a list.
reading into a list of objects
reader = new Scanner(new File("sales.txt"));
List<Trans> transList = new ArrayList<>();
int i = 0;
while(reader.hasNext()) {
Trans trans = new Trans();
trans.transID = Integer.parseInt(reader.next());
trans.transCode = Integer.parseInt(reader.next());
trans.time = reader.next();
trans.trasAmount = Double.parseDouble(reader.next());
transList.add(trans);
i++;
}
reader.close();
for(Trans trans : transList) {
System.out.println("" + i++ + ": " + trans);
}
Output of all 3 methods
0: 350279, 1, 11:54, 107.15
1: 350280, 3, 11:55, 81.27
2: 350281, 2, 11:57, 82.11
3: 350282, 0, 11:58, 92.43
4: 350283, 3, 11:59, 86.11
Here is a sample code to read the values from the file and write into an array. Sample code has logic for int array, you can replicate it for other array types as well.
package sales;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
public class Sales {
public static void main (String[] args) throws IOException {
FileInputStream fstream = new FileInputStream("sales.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
String strLine;
while ((strLine = br.readLine()) != null) {
String[] tokens = strLine.split(" ");
int[] transID = convertStringToIntArray(tokens[0]);
for(int i = 0 ; i < transID.length ; i++ )
System.out.print(transID[i]);
}
}
/** function to convert a string to integer array
* #param str
* #return
*/
private static int[] convertStringToIntArray(String str) {
int intArray[] = new int[str.length()];
for (int i = 0; i < str.length(); i++) {
intArray[i] = Character.digit(str.charAt(i), 10);
}
return intArray;
}
}

Java StringTokenizer

I have the following input
(11,C) (5,) (7,AB)
I need to split them into 2 part for each coordinates.
So my intarray should have 11, 5, 7
and my letter array should have C,,AB
But when I try using stringtokenizer,
I only get my intarray should have 11, 5, 7
and my letter array should have C,AB
Is there any way I could get the empty part of (5,)?
Thank you.
Vector<String> points = new Vector<String> ();
String a = "(11,C) (5,) (7,AB)";
StringTokenizer st = new StringTokenizer(a, "(,)");
while(st.hasMoreTokens()) {
points.add(st.nextToken());
}
}
System.out.println(points);
List <Integer> digits = new ArrayList <Integer> ();
List <String> letters = new ArrayList <String> ();
Matcher m = Pattern.compile ("\\((\\d+),(\\w*)\\)").matcher (string);
while (m.find ())
{
digits.add (Integer.valueOf (m.group (1)));
letters.add (m.group (2));
}
Must be like this
String[] values = a.split("\\) \\(");
String[][] result = new String[values.length][2];
for (int i = 0; i < values.length; i++) {
values[i] = values[i].replaceAll("\\(|\\)", "") + " ";
result[i] = values[i].split("\\,");
System.out.println(result[i][0] + " * " + result[i][1]);
}
result will contain coordinate pairs.
public static void main(String[] args) {
String s = "(11,C), (5,) ,(7,AB)";
ArrayList<String> name = new ArrayList<String>();
ArrayList<Integer> number = new ArrayList<Integer>();
int intIndex = 0, stringIndex = 0;
String[] arr = s.split(",");
for (int i = 0; i < arr.length; i++) {
String ss = arr[i].replace("(", "");
ss = ss.replace(")", "");
boolean b = isNumeric(ss);
// System.out.println( Arrays.toString(arr));
if (b) {
int num = Integer.valueOf(ss.trim()).intValue();
number.add(num);
} else
name.add(ss);
}
System.out.println(name);
System.out.println(number);
}
public static boolean isNumeric(String str) {
try {
double d = Double.parseDouble(str);
} catch (NumberFormatException nfe) {
return false;
}
return true;
}
Try this: I have slightly changed the input from "(11,C) (5,) (7,AB)" to "(11,C), (5,) ,(7,AB)" .
Output:
[C, , AB]
[11, 5, 7]
Brutal coding, in raw level:
List<String> points = new ArrayList<String> ();
String source= "(11,C) (5,) (7,AB)";
StringTokenizer deleteLeft = new StringTokenizer(source, "(");
while(deleteLeft.hasMoreTokens()) {
StringTokenizer deleteRight = new StringTokenizer(deleteLeft.nextToken(), ")");
points.add(deleteRight.nextToken());
}
System.out.println(points);
}

Categories

Resources