Loop issue on reading from file - java

I am having trouble with my loop. If anyone could take a look and try to find where im going wrong it would be awesome. I am reading from two different files and I want my code to loop through the entire files. So far it is only looping the first 11 lines of the file.
package lab.pkg02;
import java.util.Scanner;
import java.io.*;
public class Lab02 {
public static void main(String[] args) throws IOException {
File usageFile;
File historyFile;
PrintWriter resultsFile;
PrintWriter newHistoryFile;
Scanner usageSC,historySC;
String vin,make,model;
int year, beginingOdo, endingOdo, currentGallons, currentGas,
currentRepair, mpg, costPerMile, totalGas, totalRepair,
currentMiles;
//Display Report Heading to Report File
resultsFile = new PrintWriter("reportfile.txt");
resultsFile.printf("%-5s%10s%15s%12s%13s%16s%5s%16s%17s%20s\n", "VIN",
"Vehicle Description", "Beginning Odo",
"Ending Odo", "Current Gas","Current Repair", "MPG",
"Cost Per Mile", "Historical Gas", "Historical Repair");
//Process Each Vehicle
for(int cnt = 0; cnt < 15; cnt++) {
//Get Vehicle Information from Usage File
usageFile = new File("usage.txt");
usageSC = new Scanner(usageFile);
vin = usageSC.nextLine( );
year = usageSC.nextInt( );
usageSC.nextLine();
make = usageSC.nextLine( );
model = usageSC.nextLine( );
beginingOdo = usageSC.nextInt( );
usageSC.nextLine();
endingOdo = usageSC.nextInt( );
usageSC.nextLine();
currentGallons = usageSC.nextInt( );
usageSC.nextLine();
currentGas = usageSC.nextInt( );
usageSC.nextLine();
currentRepair = usageSC.nextInt( );
usageSC.nextLine();
mpg = usageSC.nextInt( );
usageSC.nextLine();
costPerMile = usageSC.nextInt( );
usageSC.close( );
//Get Vehicle History from History File
historyFile = new File ("historyfile.txt");
historySC = new Scanner(historyFile);
vin = historySC.nextLine( );
totalGas = historySC.nextInt( );
historySC.nextLine();
totalRepair = historySC.nextInt( );
historySC.nextLine();
historySC.close( );
//Calculate Updated Vehicle Information
currentMiles = endingOdo - beginingOdo;
mpg = currentMiles / currentGallons;
costPerMile = (currentGas + currentRepair) / currentMiles;
totalGas = totalGas + currentGas;
totalRepair = totalRepair + currentRepair;
//Store Updated Vehicle Information to New History File
newHistoryFile = new PrintWriter("newhistoryfile.txt");
newHistoryFile.println(vin);
newHistoryFile.println(totalGas);
newHistoryFile.println(totalRepair);
newHistoryFile.close( );
//Display Vehicle Summary Line to Report File
resultsFile.printf("%-5s%10s%15s%12s%13s%16s%5s%16s%17s%20s\n", vin,
year,make,model, beginingOdo,endingOdo, currentGas,currentRepair, mpg
,costPerMile, totalGas, totalRepair);
resultsFile.close( );
}
}
}
Both files are posted below im sure that the issue of the loop is not because of the file but do to an error in the code.
****Usage File*****
1FTSW2BR8AEA51037
2017
Ford
Fiesta
12345
123456
200
2500
50
40
100
4S7AU2F966C091212
2016
Ford
Focus
2356
23567
80
150
10
30
101
1FTEX1EM9EFD29979
2015
Ford
Mustang
23
235
86
100
30
29
102
1XPVD09X5AD163651
2015
Ford
Escape
15000
235679
800
350
750
28
103
2G1WF5EK0B1163554
2014
Ford
Explorer
7854
12498
736
259
123
27
104
1GDP8C1Y7GV522436
2013
Audi
A6
5269
54697
456
2464
61431
26
104
1FMCU92709KC54353
2012
Audi
A8
123
3456
52
86
10
25
106
1GDHK44K59F125839
2011
Audi
TT
5689
46546
14
89
15
24
107
3GYFNBE38ES603704
2010
Audi
Q5
54875
646656
69
84
1000
23
108
SAJPX1148VC828077
2009
Audi
R8
1201
1209
213
1321
11000
25
109
JS2RF9A72C6152147
2008
Audi
A7
2589
36644
874
1511
110
41
111
JT2SK13E4S0334527
BMW
2007
i8
652
3664
856
151
11
26
110
1GTHC34K6KE580545
BMW
2006
X6
65
324
231
1636
11136
19
112
1FDNS24L0XHA16500
BMW
2005
X1
546
64654
2654
16354
112
21
113
2C3AA53G55H689466
BMW
2004
M4
1233
6464
264
1354
12
32
114
*****historyfile*******
1FTSW2BR8AEA51037
4500
150
4S7AU2F966C091212
2150
1000
1FTEX1EM9EFD29979
10000
15000
1XPVD09X5AD163651
3500
7500
2G1WF5EK0B1163554
2590
1230
1GDP8C1Y7GV522436
24640
614310
1FMCU92709KC54353
860
100
1GDHK44K59F125839
8909
150
3GYFNBE38ES603704
8408
10000
SAJPX1148VC828077
132107
110000
JS2RF9A72C6152147
151106
1100
JT2SK13E4S0334527
15105
110
1GTHC34K6KE580545
163604
111360
1FDNS24L0XHA16500
1635403
1120
2C3AA53G55H689466
135402
1201

From what I see, you are re-initializing
usageFile = new File("usage.txt");
usageSC = new Scanner(usageFile);
historyFile = new File ("historyfile.txt");
historySC = new Scanner(historyFile);
newHistoryFile = new PrintWriter("newhistoryfile.txt");
in every loop which runs 15 times, and you close the scanner in each loop.
Move those outside the loop and it will work and change nextLine() to next() to read next strings for usage.
Your file has empty lines after the 11th vin in usage.

Related

What is the parseBase64Binary function in Python?

In Java, I use:
String str = “%EF!c&WrDwCCTe<fX$,#8L<YTs?G5d>F])ub.63G=Xn<cdef2R{47JQexxN”;
byte[] result = DatatypeConverter.parseBase64Binary(str);
for(byte i : result){
System.out.print(i);
System.out.print(" ");
}
to decode str.
Output:
16 87 22 -84 60 2 9 55 -97 95 -62 -40 78 -63 -71 116 91 -101 -21 113 94 119 29 121 -3 -111 -29 -78 80 123 28 77
Now I need to decode str with Base64 in python but I don't know which lib and function should I choose.
I've tried base64.b64decode but its result is different from that in Java.
str = '%EF!c&WrDwCCTe<fX$,#8L<YTs?G5d>F])ub.63G=Xn<cdef2R{47JQexxN'
result = base64.b64decode(str)
print(result)
for i in range(0, len(decode_secret)):
print(decode_secret[i], end=" ")
Output:
b'\x10W\x16\xac<\x02\t7\x9f_\xc2\xd8N\xc1\xb9t[\x9b\xebq'
16 87 22 172 60 2 9 55 159 95 194 216 78 193 185 116 91 155 235 113

for loop iteration cant find whats making i jump values

FILE THATS BEING READ
Rob Gronkowski 48
Zach Ertz 34
Travis Kelce 29
Evan Engram 15
Jimmy Graham 12
Cameron Brate 10
Delanie Walker 9
Kyle Rudolph 6
Austin Seferian-Jenkins 6
Jack Doyle 6
Hunter Henry 5
Jason Witten 4
Jordan Reed 4
Vernon Davis 3
Jared Cook 3
Tyler Kroft 3
Ed Dickson 3
Charles Clay 3
George Kittle 3
Antonio Brown 67
DeAndre Hopkins 62
A.J. Green 62
Mike Evans 62
Julio Jones 56
Michael Thomas 55
Dez Bryant 53
Michael Crabtree 45
Brandin Cooks 42
Tyreek Hill 42
Doug Baldwin 42
Keenan Allen 32
Jarvis Landry 29
Will Fuller 29
Amari Cooper 29
Stefon Diggs 29
Alshon Jeffery 27
Nelson Agholor 24
Adam Thielen 24
Chris Hogan 24
Golden Tate 24
Demaryius Thomas 22
Jordy Nelson 22
Larry Fitzgerald 22
DeSean Jackson 21
JuJu Smith-Schuster 19
Devante Parker 18
Devin Funchess 18
Kelvin Benjamin 18
T.Y. Hilton 17
Emmanuel Sanders 17
Marvin Jones 15
Rishard Matthews 14
Pierre Garcon 14
Cooper Kupp 14
Sterling Shepard 14
Paul Richardson 11
Danny Amendola 10Le’Veon Bell 70
Kareem Hunt 63
Todd Gurley 63
Leonard Fournette 60
Melvin Gordon 60
LeSean McCoy 60
Mark Ingram 50
Devonta Freeman 50
Jordan Howard 50
Lamar Miller 41
Doug Martin 34
Carlos Hyde 34
Aaron Jones 27
Alvin Kamara 27
Jerick McKinnon 24
DeMarco Murray 21
Chris Thompson 21
Jay Ajayi 21
Joe Mixon 18
C.J. Anderson 17
Tevin Coleman 17
Christian McCaffrey 17
Derrick Henry 16
Alex Collins 16
Dion Lewis 15
Adrian Peterson 13
Duke Johnson 12
Marshawn Lynch 11
Ameer Abdullah 10
Bilal Powell 9
LeGarrette Blount 9
Marlon Mack 9
James White 8
Ezekiel Elliott 7
Latavius Murray 7
Frank Gore 7
Isaiah Crowell 7
Orleans Darkwa 7
Kenyan Drake 5
Matt Forte 5
Darren McFadden 5
Alfred Morris 5
Damien Williams 3
Tarik Cohen 3
Jonathan Stewart 3
Robert Kelley 3
Danny Woodhead 3
Ty Montgomery 2
Javorius Allen 2
Mike Gillislee 2
Thomas Rawls 2
Theo Riddick 2
DeAndre Washington 2
Eddie Lacy 2
Giovani Bernard 2
Andre Ellington 2
Austin Ekeler 2
Jalen Richard 2
Ted Ginn 10
Robby Anderson 10
Jermaine Kearse 9
Davante Adams 9
Kenny Stills 9
Sammy Watkins 9
Marqise Lee 5
Mohamed Sanu 5
Allen Hurns 5
Josh Doctson 5
Jamison Crowder 4
Jeremy Maclin 3
Randall Cobb 3
Tyrell Williams 3
Robert Woods 3
Corey Davis 3
Jordan Matthews 3
Tyler Lockett 3
John Brown 2
Willie Snead 2
Donte Moncrief 2
Deshaun Watson 31
Dak Prescott 26
Tom Brady 24
Russell Wilson 22
Drew Brees 22
Carson Wentz 20
Alex Smith 14
Kirk Cousins 13
Matthew Stafford 11
Marcus Mariota 11
Tyrod Taylor 11
Cam Newton 11
Matt Ryan 11
Philip Rivers 8
having some problems been looking all over for answers. I found out my for loop iteration is incorrect it prints the series:0,1,2,10 etc. I was wondering if someone can point out my flaw, so I can fix this. I apprectiate anyone reading this, and appolgozie for the length of code. But just wanted to include everything so I don't miss anything. FOR LOOP LINE 87 thanks again, sincerely java noob
CODE
package trades;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.Scanner;
import java.util.regex.*;
public class Fantasy {
public static void main(String[] args) {
int[] playerRanking = new int[75];
String infoComingIn = null;
//Finding file path
String filename = "C:\\Users\\Karanvir\\Desktop\\21days\\players.txt";
File filez = new File(filename);
BufferedReader br;
String[] playerNames = new String[75];
int counterOfReadLines = 0;
Pattern p = Pattern.compile("[0-9]{2,3}");
ArrayList<Integer> arrayList = new ArrayList<Integer>();
try {
br = new BufferedReader(new FileReader(filez));
playerNames[counterOfReadLines] = br.readLine();
while (br.readLine() != null) {
counterOfReadLines = counterOfReadLines + 1;
playerNames[counterOfReadLines] = br.readLine();
System.out.println(playerNames[counterOfReadLines - 1]);
}
br.close();
for (int i = 0; i < playerNames.length; i++) {
Matcher m = p.matcher(playerNames[i]);
if (m.find()) {
String matched = m.group(0);
int addToArray = Integer.parseInt(matched);
playerRanking[i] = addToArray;
System.out.println(i);
}
}
} catch (Exception e) {}
}
}
Okay, so by seeing the post, I can point out only one issue. Since you are incrementing counterOfReadLines variable before the line
playerNames[counterOfReadLines] = br.readLine();
so what happens is playerNames is initializing with the array of index 1 not 0 and when you are trying to call the loop below:-
for (int i = 0; i < playerNames.length; i++) {
Matcher m = p.matcher(playerNames[i]);
if (m.find()) {
String matched = m.group(0);
int addToArray = Integer.parseInt(matched);
playerRanking[i] = addToArray;
System.out.println(i);
}
it is incrementing with 0. So either start it from i=1 or increment the counterOfReadLines after the line
playerNames[counterOfReadLines] = br.readLine();
so your error will go away...! if not let me know... :) !

HashMap keeps returning null value for no obvious reason

I have a hash map and an ArrayList. Both of them are populated as I have tried to print them out and it works fine. The arrayList contains MeterNumbers (MeterNumber is the key of the HashMap). The map contains MeterNumbers for keys and String for values.
What I want to be able to do is, get the String value from the the hasMap given the MeterNumber key which i will provide from the ArrayList. I don't think I need to check if it exists there coz I know it does for sure.I have tried all I can to get the value but it keeps giving me null values. Here is my code.
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class Try {
static Map <MeterNumber, String> map2 = new HashMap <MeterNumber, String>();
static ArrayList<MeterNumber> blackOutMeters = new ArrayList<MeterNumber>();
public static void main (String args[]) {
try {
Scanner sc2 = new Scanner(new java.io.File("meters.txt"));
Scanner sc3 = new Scanner(new java.io.File("outages.txt"));
while (sc2.hasNextLine()) {
String transformerId;
MeterNumber meterId;
String line = sc2.nextLine();
String[] array = line.split(" ");
if (array.length>3){
transformerId = array[3];
meterId = MeterNumber.fromString(array [0] + array [1] + array [2]);
map2.put(meterId, transformerId);
}
}
// System.out.println (map2.values());
while (sc3.hasNextLine()) {
MeterNumber meterId;
String line = sc3.nextLine();
String[] array = line.split(" ");
if (array.length>2){
meterId = MeterNumber.fromString(array [0] + array [1] + array [2]);
blackOutMeters.add(meterId);
}
}
for (int i = 0; i <blackOutMeters.size(); i++){
String s = map2.get(blackOutMeters.get(i));
System.out.println (s);
}
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
}}
file format for meters.txt is:
900 791 330 T1
379 165 846 T1
791 995 073 T1
342 138 557 T1
114 125 972 T1
970 324 636 T1
133 997 798 T1
308 684 630 T1
169 329 493 T1
540 085 209 T1
265 229 117 T1
970 173 664 T1
264 943 573 T1
462 043 136 T1
087 307 071 T1
001 343 243 T1
file format for outages.txt is:
900 791 330
379 165 846
791 995 073
342 138 557
114 125 972
970 324 636
133 997 798
Thank you in advance.
You need to implement hashCode and equals for MeterNumber
Otherwise Java has no way of knowing how to compare your objects

java string with extended ascii codes to byte arrary (allocate one byte per code)

I have a java nio socket server that needs to communicate with a C socket client. The C socket client sends data to the server with ASCII codes above 127, using one byte per ASCII code. The server needs to send back the same.
I need to convert a string into a byte array with the same length (one byte per code).
The string is like 1200üö001001001, where it contains some ascii codes above 127.
In the research I did, I did not find a solution. I tried this
byte[] b = "1200üö001001001".getBytes("UTF-8");
byte[] b = "1200üö001001001".getBytes("US-ASCII");
byte[] b = "1200üö001001001".getBytes("ISO-8859-1");
byte[] b = "1200üö001001001".getBytes();
Some of these convert üö into ?? or multiple bytes per ASCII code, causing a different length between byte array and string.
I needing some help.
This is an example of data that comes from the C socket client. dots are ascii codes from Client.
<code>
0000 00 ff 31 32 30 30 fc f6 00 01 08 e1 e0 00 00 00 ..1200..........
0010 00 00 14 00 00 00 31 36 34 36 30 30 32 38 30 30 ......1646002800
0020 30 30 30 30 30 34 31 38 30 31 32 30 30 30 30 30 0000041801200000
0030 30 30 30 30 30 30 31 30 30 30 30 30 30 30 30 30 0000001000000000
0040 30 30 31 30 30 30 30 30 30 30 30 30 30 30 31 30 0010000000000010
0050 30 30 36 31 30 30 30 30 30 30 36 31 30 30 30 30 0061000000610000
0060 30 30 35 31 35 39 31 31 31 34 30 39 32 33 31 33 0051591114092313
0070 32 31 31 32 33 32 30 35 31 34 30 39 32 33 30 36 2112320514092306
0080 39 39 39 39 39 39 30 30 30 30 30 35 35 31 35 39 9999990000055159
0090 31 31 33 32 39 38 20 20 20 20 33 38 38 33 33 38 113298 388338
00a0 38 33 20 20 20 20 20 20 20 42 41 43 20 50 41 4e 83 XXX PAN
00b0 41 4d 41 20 54 45 53 54 3e 48 4f 57 41 52 44 20 AMA TEST>HOWARD
00c0 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 50 P
00d0 41 30 32 33 30 30 31 30 30 31 31 30 30 32 30 30 A023001001100200
00e0 33 37 30 30 30 32 35 30 30 31 31 38 34 30 38 34 3700025001184084
00f0 30 38 34 30 30 30 30 39 31 31 30 30 30 30 30 30 0840000911000000
0100 31
This is the code i use to convert from hex string to byte array
line 4 i convert from binary eg. 1101 to equvalent hex string eg `3F`
line 13 i take the bitmap in hex string eg. `"fcf6000108e1e0000000000014000000"`
that contains 32 chars and try to convert to 16 bytes, but this results in 20 bytes
because some chars takes more than one byte
1 // Set bitmaps
2 if ( String.copyValueOf(zeros).indexOf("1", 64) == -1 ) { zeros[0] = '0'; }
3 tmp = String.copyValueOf(zeros);
4 bits = binToHex(tmp);
5
6 // check bits to send
7 if ( zeros[0] == '0') {
8 bits = bits.substring(0, 16);
9 }
10
11 // join message
12 tmp = sb.toString();
13 trm = isoCode + hexToASCII(bits) + tmp.substring(39);
14 System.out.println("Trama respuesta " + (new Timestamp((new Date()).getTime())).toString() + " " + trm);
// here the code to send back the message from nio socet to client
line mark with 100 add 2 space because there is a header with a short value that have the length of
the message to be readed by socket client
byte[] bytes = message.getBytes("ISO-8859-1");
writeLength = message.length();
//writeLength = bytes.length;
100 writeBuffer = ByteBuffer.allocate(writeLength + 2);
writeBuffer.putShort( (short)writeLength );
writeBuffer.put(message.getBytes()); // Para test
//this.writeBuffer.putChar('\n');
writeBuffer.flip();
// auxiliar methods
public String hexToASCII(String hex){
if(hex.length()%2 != 0){
System.err.println("requires EVEN number of chars");
return null;
}
StringBuilder sb = new StringBuilder();
//Convert Hex 0232343536AB into two characters stream.
for( int i=0; i < hex.length()-1; i+=2 ){
/*
* Grab the hex in pairs
*/
String output = hex.substring(i, (i + 2));
/*
* Convert Hex to Decimal
*/
int decimal = Integer.parseInt(output, 16);
sb.append((char)decimal);
}
return sb.toString();
}
private final String HEXES = "0123456789ABCDEF";
private final String HEX[] = {"0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F"};
private final String BIN[] = {"0000","0001","0010","0011","0100","0101","0110","0111","1000","1001","1010","1011","1100","1101","1110","1111"};
/*
* Convert binary to hex string
*/
public String binToHex(String bin) {
StringBuffer sb = new StringBuffer();
for (int i = 0; i < bin.length()-1 ; i += 4) {
sb.append(HEX[ArrayUtils.indexOf(BIN, bin.substring(i, (i + 4)))]);
}
return sb.toString();
}
You are mixing bytes and characters. There are dozens of ways to encode characters like ü and ö into bytes and different encodings take different amount of bytes per character.
DO NOT try to convert binary stream to string unless you know that the bytes represent textual information AND you know which encoding was used to convert the text into bytes in the first place. If the data is not a text string, DO NOT try to interpret it as a text string and just wish that every byte maps to something reasonable.
You can work directly with byte arrays or use e.g. java.nio.ByteBuffer. If there is a text string amongst the data, you can separately convert the peticular bytes into strings.
Your binary bitmap is getting mangled by character encoding conversions. There is no point in doing it that way. You can just convert from hex to byte[].
This code suggests the way:
String bitmapHex = "00112233445566778899aabbccddeeff";
String isoCode = "1200";
String data = "313030303030303031 and more";
byte[] bitmap = javax.xml.bind.DatatypeConverter.parseHexBinary(bitmapHex);
int datagramLength = 2 + isoCode.length() + bitmap.length + data.length();
ByteBuffer buffer = ByteBuffer.allocate(datagramLength);
buffer.order(ByteOrder.BIG_ENDIAN).putShort((short)datagramLength);
buffer.put(isoCode.getBytes(encodingName));
buffer.put(bitmap);
buffer.put(data.getBytes(encodingName));
byte[] output = buffer.array();

Index out of bounds exception: getting same row repeated several times

This is my code which I use to take in an Excel sheet, read its contents and to each row I add a GUID from a list I have.
UPDATE
Code:
public class PublishOutputFile {
public void publishOutputWithGuids(List<String> guids, File file)
throws Exception {
FileInputStream fileStream = new FileInputStream(file);
HSSFWorkbook workbook = new HSSFWorkbook(fileStream);
HSSFSheet sheet = workbook.getSheetAt(0);
Row toprow = sheet.getRow(0);
int cellsNum = toprow.getLastCellNum();
Iterator<Row> rowIterator = sheet.iterator();
while (rowIterator.hasNext()) {
Row row = rowIterator.next();
int rownum = row.getRowNum();
System.out.println(rownum);
Iterator<Cell> cellIterator = row.cellIterator();
while (cellIterator.hasNext()) {
Cell cell = cellIterator.next();
switch (cell.getCellType()) {
case Cell.CELL_TYPE_BOOLEAN:
break;
case Cell.CELL_TYPE_NUMERIC:
break;
case Cell.CELL_TYPE_STRING:
break;
}
if (rownum == 0) {
row.createCell(cellsNum).setCellValue("GUID");
} else {
// System.out.println(rownum);
row.createCell(cellsNum).setCellValue(guids.get(rownum-1));
}
}
}
fileStream.close();
FileOutputStream out = new FileOutputStream(
new File(
"C:/Users/U0172959/Desktop/Themes_20131120_234645-hierarchy with GUIDS.xls"));
workbook.write(out);
out.close();
}
}
UPDATE Output:
0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 286, Size: 286
at java.util.ArrayList.rangeCheck(Unknown Source)
at java.util.ArrayList.get(Unknown Source)
at mappingForEtl.PublishOutputFile.publishOutputWithGuids(PublishOutputFile.java:43)
at mappingForEtl.InputFileParsing.main(InputFileParsing.java:75)
In the output, every row is being repeated like 5 times and I think this is what causes the out of bounds exception. But I can't figure out what's causing this to happen.
(I have used the same code for a different file yesterday, and that worked fine... ) Can it have anything to do with the number of columns in the excel sheet I take as input. The one I used yesterday had 8 columns, the one I am using now has 20.
Anyone has any idea what might be causing this? Thanks for help.
You are iterating over the cells within a row and for each cell you print the row number. Are you very sure that the data you print the right values in your else case?
if (row.getRowNum() == 0) {
row.createCell(cellsNum).setCellValue("GUID");
} else {
System.out.println((row.getRowNum())); // row number for each cell?
row.createCell(cellsNum).setCellValue(guids.get((row.getRowNum())));
}
Update:
The problem with the repeated output is that you have a loop over your rows. Each row consists of a number of cells. You loop over the cells as well. The repeated output comes from the fact, that while you loop through the cells in the row, the row does not change.
For better understanding, you should change your output to that:
System.out.println("Being at row: " + row.getRowNum() + " creating cell at cellnum: " + cellsNum);
That should clean up the understanding of what is going on.
Update 2:
The IndexOutOfBoundsException is thrown because the size of guid is 286 but the index is zero based and does not start by 1. As you tread the first row different, you should change guids.get(row.getRowNum()) to guids.get(row.getRowNum() - 1). That can work but it does not have to. As long as we don't know the detailed data structure, it might be of no value for you...
About the Exception
You may have accidentaly created some new Row (probably blank) and there is no GUID on your List for that Row. That could cause this Exception.
Maybe this addition helps you:
while (rowIterator.hasNext()) {
Row row = rowIterator.next();
if (row.getLastCellNum() < cellsNum)
continue;
About the repeated output
You are iterating over each row, and then iterating over each cell, and then printing the row number. Considering a row has 4 cells, this would end up printing the Row number 4 times.
The problem is here:
} else {
row.createCell(cellsNum).setCellValue(
guids.get((row.getRowNum())));
}
Your guids.get is throwing the exception since it doesn't contain an element at index 286.
Solution: retrieve the element at index in row.getRowNum - 1, so you will now retrieve elements from 0 to 285:
} else {
row.createCell(cellsNum).setCellValue(
guids.get((row.getRowNum() - 1)));
}
Update:
Since it looks you're not trying to solve the IndexOutOfBoundsException (very odd) but more about why the numbers are printed 4 to 5 times, then review your current algorithm:
Iterator<Row> rowIterator = sheet.iterator();
//verify if there's a row to read in the current Excel sheet
while (rowIterator.hasNext()) {
//get the row
Row row = rowIterator.next();
//get an iterator of the cells
Iterator<Cell> cellIterator = row.cellIterator();
//while there's a cell to read...
while (cellIterator.hasNext()) {
//get the cell
//note: if the cell is empty, it won't be considered by the CellIterator, so even
//if you open the file and see 20 cells, this Iterator will seek for cells with some value
//from your current output, this looks to be only 5 cells
Cell cell = cellIterator.next();
//verify the type of the cell...
switch (cell.getCellType()) {
case Cell.CELL_TYPE_BOOLEAN:
//do nothing?
break;
case Cell.CELL_TYPE_NUMERIC:
//do nothing?
break;
case Cell.CELL_TYPE_STRING:
//do nothing?
break;
}
if (row.getRowNum() == 0) {
row.createCell(cellsNum).setCellValue("GUID");
} else {
//prints the number of the row (per cell)
//this causes the 1\n1\n1\n1\n2\n2\n... output
System.out.println((row.getRowNum()));
//writes the element in guids at index of row num
row.createCell(cellsNum).setCellValue(
//guids.get((row.getRowNum())));
guids.get((row.getRowNum() - 1)));
}
}
}

Categories