How to Load a file in parallel arrays in java - java

I have a file that contains 30 lines of data in this format:
month-day-year-gas price
Here's some sample data:
May 02, 1994 1.04
Can someone tell me how to load this file in a parallel arrays of months, days, price in java? After this I will have to display the lowest price, and also the highest price, and the average price for each month.

For those who are wondering:
Parallel Arrays are arrays where the data in each array is directly related to any given record data row. The index of one array contains related data at the very same index in another array. For example:
Dimension[] dim = new Dimension[4];
dim[0] = new Dimension(1,11);
dim[1] = new Dimension(2,22);
dim[2] = new Dimension(3,33);
dim[3] = new Dimension(4,44);
int[] widths = {dim[0].width, dim[1].width, dim[2].width, dim[3].width};
int[] heights = {dim[0].height, dim[1].height, dim[2].height, dim[3].height};
for (int i = 0; i < widths.length; i++) {
int w = widths[i];
int h = heights[i];
System.out.println("Width: " + w + " | Height: " + h);
}
And the Console output would be:
Width: 1 | Height: 11
Width: 2 | Height: 22
Width: 3 | Height: 33
Width: 4 | Height: 44
The widths and heights Integer Arrays are considered Parallel Arrays since the data index in each array is directly Related To and Parallel to each other. It doesn't matter which parallel array you iterate through, the current iteration is related to all other parallel arrays.
You can quickly see why it's much better to utilize a Class with Member variables for this sort of thing instead of arrays especially when a multiple number of parallel arrays are involved however, there are some practical uses for it.
The task at hand:
As you read in your file you want to use the String#split() method to break that line into the desired chunks you want. The delimiter to use here for the split() method will be a white-space (" ") or the Regular Expression (RegEx) "\\s+", for example:
"This is my String".split("\\s+");
The RegEx argument within the split() method basically means, split the string on one or more white-spaces.
In the example below the Parallel Arrays are Class Member variables. The method that fills these Arrays with the pertinent data from file is named fillParallelArraysWithFileData() and it accepts one argument, which is the path and name of the data file. Here is the code:
private static String[] monthsArray;
private static int[] daysArray;
private static int[] yearsArray;
private static double[] pricesArray;
public static void fillParallelArrayWithFileData(final String filePath) {
Scanner read = null;
try {
read = new Scanner(new File(filePath));
/* First Read Pass
===============
Get the number of VALID data lines in file.
We need this count to know how large to size
our Parallel Arrays.
*/
int lineCount = 0; // counter
while (read.hasNextLine()) {
String line = read.nextLine().trim(); // Trim lead/trailing whitespaces (if any)
/* Skip past blank or comment lines. Lines that start with
a semicolon (;) or a hash character (#) are considered
comment lines here and are ignored. You can get rid of
those conditions if you like. */
if (line.equals("") || line.startsWith(";") || line.startsWith("#")) {
continue;
}
lineCount++; // Increment the counter.
}
/* Second Read Pass
================
Get the file data and fill Arrays...
Declare Arrays which will be our parallel arrays. */
monthsArray = new String[lineCount];
daysArray = new int[lineCount];
yearsArray = new int[lineCount];
pricesArray = new double[lineCount];
int indexIncrementer = 0;
// Start the read from beginning again...
read = new Scanner(new File(filePath));
while (read.hasNextLine()) {
String line = read.nextLine();
// Remove the comma in data line. Don't want it.
line = line.trim().replace(",", "");
// If the current line is blank or a comment then skip past it.
if (line.equals("") || line.startsWith(";") || line.startsWith("#")) {
continue;
}
// Split the current data line
String[] lineParts = line.split("\\s+");
monthsArray[indexIncrementer] = lineParts[0];
daysArray[indexIncrementer] = Integer.parseInt(lineParts[1]);
yearsArray[indexIncrementer] = Integer.parseInt(lineParts[2]);
pricesArray[indexIncrementer] = Double.parseDouble(lineParts[3]);
indexIncrementer++;
}
}
catch (FileNotFoundException ex) {
System.out.println("FILE NOT FOUND! [" + filePath + "]");
}
finally {
if (read != null) {
read.close();
}
}
}
And an example usage might be:
// Fill Arrays with File data.
fillParallelArrayWithFileData("GasPrices.txt");
// Get Gas price for month of July in 1994
String desiredMonth = "July";
int desiredYear = 1994;
// We could iterate through any one of the Parallel Arrays
for (int i = 0; i < pricesArray.length; i++) {
if (monthsArray[i].equalsIgnoreCase(desiredMonth) && yearsArray[i] == desiredYear) {
String m = "Date: " + monthsArray[i] + " ";
String d = daysArray[i] + ", ";
String y = yearsArray[i] + " - ";
String p = "Gas Price: $" + pricesArray[i];
System.out.println(m + d + y + p);
}
}
Output to console window would be something like:
Date: July 2, 1994 - Gas Price: $1.12

Related

How to properly initialize an ArrayList of an ArrayList of Integers read from input file [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
I need to parse an input file with this format. The input file can be of any size, so I decided to go with Lists rather than arrays. I need to store it an array after the data is parsed. It represents RGB values. E.g. this snippet is a 2x2 pixel image.
[251,255,128],[132,244,121]
[125,156,155],[157,200,090]
public class RGBFileReader {
public static void main(String[] args) {
String filename;
filename = args[0];
new RGBFileReader().ReadRGBfile(filename);
} // end main method block
// declare the class constructor, pass filename parameter and initialize variables
public void ReadRGBfile (String filename) {
int rowCount = 0;
int columnCount = 0;
int columnIndex = 0;
//2D List = ArrayList of an ArrayList of Integers. ArrayList stores Objects not "ints"!
ArrayList<ArrayList<Integer>> rgbArrayList = new ArrayList<ArrayList<Integer>>();
try {
//confirm current working directory for I/O files
System.out.println("parsing input file at path: " + new File(".").getAbsoluteFile()+ filename);
// pass the path to the file as a parameter
File file = new File("input/" + filename);
Scanner myScanner = new Scanner(file);
// pattern match to sequence of comma delimited integers inside square brackets: [+/-int,+/-int,+/-int]
// -? = once or not at all, and minus sign handles negative numbers (although not strictly needed in this context)
String patternToMatch = "\\[(-?\\d+),(-?\\d+),(-?\\d+)\\]";
Pattern pattern = Pattern.compile(patternToMatch);
// [\\d] = any digit, note need a second backslash to escape first backslash which is a java escape character
// + = 1 or more occurrences
String innerpatternToMatch = "(\\d+)";
Pattern innerpattern = Pattern.compile(innerpatternToMatch);
while (myScanner.hasNextLine()) { // while loop to scan each line of input file
ArrayList<Integer> singleRow = new ArrayList<Integer>();
columnIndex = 0;
System.out.println("rowCount: " + rowCount);
String line = myScanner.nextLine();
Matcher matcher = pattern.matcher(line);
while (matcher.find()) { // outer while to parse groups of brackets
System.out.println("columnCount: " + columnCount);
String outerline = matcher.group();
System.out.println("outerline: " + outerline);
Matcher innermatcher = innerpattern.matcher(outerline);
while (innermatcher.find()) { // inner while to parse triplets within brackets
String innerline = innermatcher.group();
System.out.println("innerline: " + innerline);
singleRow.add(Integer.valueOf(innermatcher.group())); //add triplets one at a time to inner List "oneRow"
System.out.println("singleRow = " + singleRow);
columnIndex++;
} //end inner inner while
columnCount = columnIndex;
} // end outer while
rgbArrayList.add(singleRow); // add the oneRow of triplets, to the outer List "twodimArrayList"
System.out.println("rgbArrayList dump using toString(): " + rgbArrayList.toString());
System.out.println("\n");
rowCount++;
} // end scanner while loop
myScanner.close();
System.out.println("scanner is closed...");
} // end Try block
catch (FileNotFoundException e) {
System.err.println("Could not open RGB input file: check it exists, is in the file path, or has correct format.");
} //end catch block
//sanity check for correct values of rowCount and columnCount
System.out.println("\n");
System.out.println("rowCount: " + rowCount);
System.out.println("columnCount: " + columnCount);
// Parsing of input file complete, now declare int[][] array
int [][] rgbArray = new int [rowCount][columnCount];
// check for expected values properly stored in ArrayList
System.out.println("\n");
System.out.println("List<Integer> rgbArrayList values using iterator" );
Iterator<ArrayList<Integer>> iterator = rgbArrayList.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
//Initialize the int [][] Array using values from the ArrayList
System.out.println("\n");
for (int row = 0; row < rowCount; row++) {
for (int col = 0; col < columnCount; col++) {
rgbArray[row][col] = rgbArrayList.get(row).get(col).intValue();
} // end inner for loop
} // end outer for loop
System.out.println("rgbArray values");
for (int i = 0; i < rowCount; i++) {
System.out.println(Arrays.toString(rgbArray[i]));
} // end inner loop
} // end method ReadRGBfile
} // end class
There isn't really such a thing as a 2D ArrayList. You are creating a List of Lists, which means each element of the outer List must be a new ArrayList<Integer> and all inner Lists do not need to be the same size as one another. Try moving your singleRow declaration down inside of the while loop and removing singleRow.clear();
As a side note, it isn't necessary to use an index when you add to a List. twodimArrayList.add(singleRow); will add to the end of the List.

Reading a file with Strings and floats and assigning them to arrays

I want to design a code that can read a file that looks like this:
Jake 12.00 13.24 6
Sarah 11.23 24.01 8
Alex 10.65 19.45 4
I need to make separate arrays for the Strings, the first float, the second float, and the int.
How do I go about doing this?
This is what I have so far: I'm not sure how to make separate arrays for the two floats. I also keep getting an exception IndexOutOfBoundsException: 0 at EmployeePay.main..
import java.util.Scanner;
import java.io.*;
public class EmployeePay {
public static void main(String[] args) throws FileNotFoundException {
if (args.length != 1) {
final String msg = "Usage: EmployeePay name_of_input file";
System.err.println(msg);
throw new IllegalArgumentException(msg);
}
final String inputFileName = args[0];
final File input = new File (inputFileName);
final Scanner scanner = new Scanner(new BufferedReader(new FileReader(input)));
String Id = "Employee Id:";
String Hours = "Hours worked:";
String WageRate = "Wage Rate:";
String Deductions = "Deductions:";
System.out.printf("%s %-10s %-20s %-30s", Id, Hours, WageRate, Deductions);
int lineNumber = 0;
while (scanner.hasNextLine()){
lineNumber =lineNumber +1;
String [] Identification= new String [lineNumber-1];
int [] TotalDeductions = new int [lineNumber-1];
float [] WorkTime = new float[lineNumber-1];
if(scanner.hasNextInt()){
TotalDeductions[lineNumber-1] = scanner.nextInt();
System.out.println(TotalDeductions[lineNumber-1]);
}
else if (scanner.hasNextFloat()){
WorkTime[lineNumber-1]= scanner.nextFloat();
}
else {
Identification[lineNumber-1] = scanner.next();
System.out.println(Identification[lineNumber-1]);
}
}
}
}
I will assume your String value doesn't contain space. This is kind of pseudo code, Try yourself and explore each line why I did so:
String s[] = new String[size];
float f1[] = new float[size];
float f2[] = new float[size];
for(int i=0; i<numberOfLines;i++) {
String x = "Jake 12.00 13.24 6";
String[] arr = x.split(" ");
s[i] = arr[0];
f1[i] = Float.valueOf(arr[1]);
f2[i] = Float.valueOf(arr[2]);
}
This error exception IndexOutOfBoundsException: 0 at EmployeePay.main. is occuring due to this statement if (args.length != 1).
It should be if(args.length!=0)
If no arguements are passed at command prompt then args.length is 0. So, this statement will throw an exception final String inputFileName = args[0];
Thus, you need to check for args.length
If your data file is indeed as you show in your post with blank lines between the data lines then you will need to take care of those as well while reading the file and processing the information obtained. You obviously want to skip past those particular lines. If this isn't the case then it only goes to show you how important it is to provide full and accurate information when asking a question here. No one here wants to really assume anything.
When creating arrays it's always nice to know how big an array needs to be beforehand so that you can properly initialize it to its required size. This is where List or ArrayList is better, you can just add to them when needed. Never the less, to properly initialize all your different arrays (String[], float[], float[], and int[]) you need to know how many valid data line are contained within your data file. By valid data lines I mean lines that actually contain data, not blank lines. So the first natural step would be to count those lines. Once you have the count then you can initialize all your arrays to that line count.
Now all you need to do is re-read the file data line by line, split each line to acquire the data segments , then convert each numerical segment to its respective Array data type. Once you have all your arrays filled from the file you can then do whatever you like with the data contained within those arrays. The code to carry out this task might look something like this:
String inputFileName = "MyDataFile.txt";
Scanner scanner;
int linesCount = 0;
try {
// Count the total number of valid data lines
// within the file (blank line are skipped).
scanner = new Scanner(new File(inputFileName));
while (scanner.hasNextLine()) {
String strg = scanner.nextLine().trim();
if (!strg.equals("")) { linesCount++; }
}
// Declare our different Arrays and size them to
// the valid number of data lines in file.
String[] employeeID = new String[linesCount];
float[] hours = new float[linesCount];
float[] wageRate = new float[linesCount];
int[] deductions = new int[linesCount];
// Read through the file again and place the data
// into their respective arrays.
scanner = new Scanner(new File(inputFileName));
int counter = 0;
while (scanner.hasNextLine()){
// Get the next line in file...
String strg = scanner.nextLine().trim();
// If the file line is blank then skip it.
if (strg.equals("")) { continue; }
// otherwise split the line by its space
// delimiter ("\\s+" takes care of 1 OR more
// spaces just in case).
String[] values = strg.split("\\s+");
// Add to the employeeID string array.
employeeID[counter] = values[0];
// Control what is placed into the elements of each
// float or integer array. If there is no value data
// supplied in file for the employee Name then make
// sure 0.0 (for floats) or 0 (for integers) is placed
// there after all, you can't parse a null string ("").
if (values.length >= 2) { hours[counter] = Float.parseFloat(values[1]); }
else { hours[counter] = 0.0f; }
if (values.length >= 3) { wageRate[counter] = Float.parseFloat(values[2]); }
else { wageRate[counter] = 0.0f; }
if (values.length == 4) { deductions[counter] = Integer.parseInt(values[3]); }
else { deductions[counter] = 0; }
counter++;
}
scanner.close();
// Now that you have all your arrays you can
// do whatever you like with the data contained
// within them:
String Id = "Employee Id:";
String Hours = "Hours worked:";
String WageRate = "Wage Rate:";
String Deductions = "Deductions:";
System.out.printf("%-15s %-15s %-15s %-15s%n", Id, Hours, WageRate, Deductions);
for (int i = 0; i < employeeID.length; i++) {
System.out.printf("%-15s %-15s %-15s %-15s%n", employeeID[i], hours[i], wageRate[i], deductions[i]);
}
}
catch (FileNotFoundException ex) { ex.printStackTrace(); }

Epson epos sdk receipt alignment issue

i'm currently using epson ePOS SDK for android.
i need to print the receipt that menu name align to the left and its price align to the right in the same line but it doesn't work properly,
my temporary solution is add some feed line to make its price align right, is it possible to have both text align left and right in the same line ?
(Attachments below and please ignore question mark symbols)
mPrinter.addTextAlign(Printer.ALIGN_LEFT);
mPrinter.addFeedLine(0);
textData.append(menuName);
mPrinter.addText(textData.toString());
textData.delete(0, textData.length());
mPrinter.addFeedLine(0);
//print price
mPrinter.addTextAlign(Printer.ALIGN_RIGHT);
textData.append(price + "Y" + "\n");
mPrinter.addText(textData.toString());
textData.delete(0, textData.length());
mPrinter.addFeedLine(0);
80mm is like 42 columns per line ...which can be easily padded:
mPrinter.addText(padLine(menuName, price + "¥", 42) + "\n");
the required String manipulation methods look alike:
/** utility: pads two strings to columns per line */
protected String padLine(#Nullable String partOne, #Nullable String partTwo, int columnsPerLine){
if(partOne == null) {partOne = "";}
if(partTwo == null) {partTwo = "";}
String concat;
if((partOne.length() + partTwo.length()) > columnsPerLine) {
concat = partOne + " " + partTwo;
} else {
int padding = columnsPerLine - (partOne.length() + partTwo.length());
concat = partOne + repeat(" ", padding) + partTwo;
}
return concat;
}
/** utility: string repeat */
protected String repeat(String str, int i){
return new String(new char[i]).replace("\0", str);
}
one should format the price to currency, before padding it.
to make it truly "flawless" ... when String concat exceeds length 42, then String partOne should be truncated by the excess length - and be concatenated, once again. exceeding int columnsPerLine will most likely mess up the output.
Inserting the RIGHT string in the LEFT string at an appropriate position. This is because I'm not using a feedLine provided by EPSON. Instead I'm manually adding a new line(\n) after 42(this varies according to the printer) characters.
// gap -> Number of spaces between the left and the right string
public void print(Printer epsonPrinter, String left, String right, int gap) throws Epos2Exception {
int total = 42;
// This is to give a gap between the 2 columns
for (int i = 0; i < gap; i++) {
right = " " + right;
}
// This will make sure that the right string is pushed to the right.
// If the total sum of both the strings is less than the total length(42),
// we are prepending extra spaces to the RIGHT string so that it is pushed to the right.
if ((left.length() + right.length()) < total) {
int extraSpace = total - left.length() - right.length();
for (int i = 0; i < extraSpace; i++) {
left = left + " ";
}
}
int printableSpace = total - right.length(); // printable space left for the LEFT string
//stringBuilder -> is the modified string which has RIGHT inserted in the LEFT at the appropriate position. And also contains the new line. This is the string which needs to be printed
StringBuilder stringBuilder = new StringBuilder();
// Below 2 statements make the first line of the print
stringBuilder.append(left.substring(0, Math.min(printableSpace, left.length())));
stringBuilder.append(right);
// stringBuilder now contains the first line of the print
// For appropriately printing the remaining lines of the LEFT string
for (int index = printableSpace; index < left.length(); index = index + (printableSpace)) {
stringBuilder.append(left.substring(index, Math.min(index + printableSpace, left.length())) + "\n");
}
epsonPrinter.addText(stringBuilder.toString());
}

How can I format a two row string so that items of the bottom row line up with items of the top row in java

So I have something set up like this:
public static void main(String[] args) {
String fun = ("3000.05 500 6000.987 70 8000.00");
String lame = ("3 5 6 7 8");
String total = (fun + "\n" + lame);
System.out.println(total);
}
How can I format the total string so that when it prints it prints like this:
3000.05 500 6000.987 70 8000.00
3 5 6 7 8
I've been looking forever and can't seem to find what i'm looking for. I'm just trying to right align each part of the bottom string to the farthest part of the top string.
you can use a for loop to go through each position on the string and create a new String to store what you are looking for. Ex.
public static void main(String[] args) {
String fun = ("3000.05 500 6000.987 70 8000.00");
String newStringToBePrinted="";
for(char c: fun){
if (!(c == ' '|| c == '.')){
String ch = c+"";
newStringToBePrinted+= ch;
} else{
newStringToBePrinted+="-";
}
}
String total = (fun + "\n" + newStringToBePrinted);
System.out.println(total);
}
hope this helps.
Here is how you can do this with (moderately) readable Stream code. The below method will work, but it's a bit ugly because AFAIK Java 8 does not yet have a clean 'zip' function for streams.
As well, because of the way String.format() works, I had to pad the first thing in the list separately, which is also kind of yucky, but I couldn't quickly think of a way to make it all fit.
private String formatStringPairs(String firstLine, String secondLine, String delimiter) {
String[] firstLineArray = firstLine.split(delimiter);
String[] secondLineArray = secondLine.split(delimiter);
String formattedStringPairs =
String.format("%" + firstLineArray[0].length() + "s", secondLineArray[0]) +
IntStream.range(1, firstLineArray.length)
.mapToObj(index -> String.format("%" + (firstLineArray[index].length() + 1) + "s", secondLineArray[index]))
.reduce("", String::concat);
return firstLine + "\n" + formattedStringPairs;
}
I look forward to seeing someone post a cleaner and better way!
This should work. I believe temp is the recreation of your variable lame but the code would be the same.
package funTest;
public class funT {
public static void main(String[] args) {
String fun = ("3000.05 500 6000.987 70 8000.00");
String s2 = new String(fun);
char first=' ';
String temp="";
for (int i = 0;i < s2.length(); i++){
System.out.println("Should be: 3,5,6,7,8");
//gets first
if (i!=0){
if (s2.charAt(i)==' '){
first=s2.charAt(i+1);
}
}else{
first=s2.charAt(i);
}
System.out.println("First = "+first);
/////
//add spaces
if (s2.charAt(i)!=' '){
temp+=' ';
}
if (i<s2.length()-1&&s2.charAt(i+1)==' '){
temp+=first;
} else if (i==s2.length()-1){
temp+=first;
}
}
temp = temp.substring(1);
System.out.println(s2+"\n"+temp);
}
}
Ok so tldr. Use the .format() method of PrintStream (for byte streams) or PrintWriter (for char streams)
Luckily System.out is one of these objects. Documentation for format can be found here
Here is a nice demonstration of using .format() I mentioned for your purpose, this code assumes the two strings have an equal number of numbers separated by whitespace. It also assumes that the second-row item length will be <= in length to its' first-row counterpart
public static void main(String[] args)
{
String fun = "3000.05 500 6000.987 70 8000.00";
String lame = "3 5 6 7 8";
String[] funs = fun.split(" ");
String[] lames = lame.split(" ");
for(String s : funs)
{
System.out.printf("%s\t", s);
}
System.out.printf("%n");
for(int i = 0; i < lames.length; i++) //use index iterator so we can get le funz
{
System.out.printf("%" + funs[i].length() + "s\t", lames[i]);
}
System.out.printf("%n");
}
Output:
run:
3000.05 500 6000.987 70 8000.00
3 5 6 7 8
BUILD SUCCESSFUL (total time: 0 seconds)
To improve this code more It might be possible to associate the first row and second row in a Map type object, and then when printing: set the padding size
to the size of the entry key or value which has the greatest length. Also add a handler for empty entries.

Add one number from an array to another (by column)

I have been trying to figure out how to add one number in an array to another number in an array. I parsed the numbers in a String into integers, and separated them by columns. Then, I added each column into an array.
What I would like to solve is how to add all the numbers in a column.
The numbers are from a text file.
// numbers.txt:
Bob, 100, 98, 95
Alex, 85, 90, 92
I already used bufferedReader and parsed the numbers, from String to int.
The challenge is adding the numbers by column.
For example, if there are 3 numbers in each array, I just want to add the first numbers in each array.
Q1 is [100, 98, 95]
Q2 is [85, 90, 92]
Only 100 + 85 together.
Below are the codes that I have so far.
Any help on how to proceed will be awesome! Thanks for your time.
int Q1 = Integer.parseInt(columns[1]);
int Q2 = Integer.parseInt(columns[2]);
ArrayList<Integer> Q1list = new ArrayList<>();
Q1list.add(Q1);
Q1list.add(Q2);
double total = 0.0;
for (int i = 0; i < Q1list.size(); i++) {
total += Q1list.get(i);
}
System.out.println(total);
Well, usually when you want to add up the numbers from the array in to a sum you want to iterate over all the indexes in that array. From the loop you've written I cannot see going to all the numbers into the array in any way.
Please revise how for loop is used!
Here is a good explanation, hope it helps
Java: Array with loop
I think you should have at least 2 columns array.
After don't forget your index (in your loop)
Code suiggested:
public static void main(String[] args) {
int [] q1 = { 100 , 98 , 95 };
int [] q2 = { 85 , 90 , 92 };
List<Integer> sumList = new ArrayList<>();
// First solution (what you ask)
sumList.add( q1[0] + q2[0] );
System.out.println("Add Q1[0] + Q2[0]: " + sumList.get(0));
// Second solution (add all)
for( int i = 0 ; i < q1.length ; i++)
{
sumList.add(q1[i] + q2[i]);
}
// Check your result
for( int i : sumList )
System.out.println("Result: " + i);
}
And result gives:
// First solution (what you ask)
Add Q1[0] + Q2[0]: 185
// Second solution (add all)
Result: 185
Result: 185
Result: 188
Result: 187
I find what you want:
// Scanner
StringTokenizer i1 = new StringTokenizer(" [100,98,95]", "[,]");
StringTokenizer i2 = new StringTokenizer(" [85,90,92]", "[,]");
List<Integer> q1List = new ArrayList<>();
List<Integer> q2List = new ArrayList<>();
while( i1.hasMoreTokens() ){
try {
Integer intRes = Integer.parseInt(i1.nextToken());
System.out.println("Test1: " + intRes);
q1List.add(intRes);
}
catch( NumberFormatException e) {}
}
while( i2.hasMoreTokens() ){
try {
Integer intRes = Integer.parseInt(i2.nextToken());
System.out.println("Test2: " + intRes);
q2List.add(intRes);
}
catch( NumberFormatException e) {}
}
// Second solution (add all)
for( int i = 0 ; i < q1List.size() ; i++)
{
sumList.add(q1List.get(i) + q2List.get(i));
}
// Check your result
for( int i : sumList )
System.out.println("Result 2 : " + i);
Sorry for the long time but I have to find on web the answer.
Simples reads file line by line and set new string for each new line...
After that, for each string you can use Strink tokenizer with delimiter in your case : ",".
Take carefull that your first parameter shall be:
null (code for that)
name (catch this string)
other (maybe try catch)
I find this link on stack:
Using Java 8, what is the most preferred and concise way of printing all the lines in a file?
Good luck

Categories

Resources