Write and Read binary file - java

I have a test: Write number from 50000 to 60000 to file with any format, then read this data to original number (file size limit 20kb) and cannot use writeShort() method to write or read. But i cannot read file to original number, my code below:
This is write
DataOutputStream out = new DataOutputStream(new FileOutputStream("D:\\mydata2.txt"));
for (int i = 50000; i <= 60000; i++) {
out.write(i);//write() just write 8-bit
}
out.close();
This is read
DataInputStream in = new DataInputStream(new FileInputStream("D:\\mydata2.txt"));
int i=0;
while (in.available() > 0) {
System.out.print(in.readUnsignedByte()+" ");
}
in.close();
Output like this:
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 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

Here's your clue for the 'hard part'. You must do the rest:
byte[] buf = new byte[2];
// (In loop)
buf[0] = (byte)(n >> 8);
buf[1] = (byte)(n & 0xFF);

This is the correct way to do it:
You do not write short, but you write the bytes of it. And the same logic for read too.
DataOutputStream out = new DataOutputStream(new FileOutputStream("C:\\New\\mydata2.txt"));
for (int i = 50000; i <= 60000; i++)
{
ByteBuffer dbuf = ByteBuffer.allocate(2);
dbuf.putShort((short) i);
byte[] bytes = dbuf.array();
out.writeByte(bytes[0]);
out.writeByte(bytes[1]);
}
out.flush();
out.close();
DataInputStream in = new DataInputStream(new FileInputStream("C:\\New\\mydata2.txt"));
byte[] buf = new byte[2];
while (in.available() > 0)
{
buf[0] = in.readByte();
buf[1] = in.readByte();
// Since Short keyword cannot be used, we could use the following way to get the numbers:
int num = (0xff & buf[0]) << 8 |
(0xff & buf[1]);
System.out.print(num +" ");
}
in.close();
Check this to understand the last conversion with shift operators.

Related

Using priority queue with File Reader

I want to order numbers between the range of 1-100 with File Reader. It's very weird otput. My code:
import java.io.*;
import java.util.*;
public class Main {
public static String strLine;
public static int order = 1;
public static void main(String[] args) {
Queue<String> queue = new PriorityQueue<String>();
try{
FileReader fr = new FileReader("File.txt");
BufferedReader br = new BufferedReader(fr);
while ((strLine = br.readLine()) != null) {
queue.offer(strLine);
}
br.close();
} catch (IOException e){
System.out.println("File not found");
}
while (!queue.isEmpty()){
System.out.println(order + ".Number: " + queue.poll());
order++;
}
} }
File.txt:
81
56
42
3
49
100
61
76
74
79
6
90
34
93
22
71
72
63
67
18
14
5
91
39
53
86
40
45
60
55
48
62
8
4
80
11
87
47
15
46
97
66
43
58
41
54
33
96
82
44
98
27
85
10
32
95
35
24
7
30
83
9
31
99
25
29
57
36
69
50
28
59
12
37
78
73
70
89
65
51
77
88
20
17
21
94
64
19
26
23
92
52
2
16
68
75
38
1
84
13
output:
1.Number: 1
2.Number: 10
3.Number: 100
4.Number: 11
5.Number: 12
6.Number: 13
7.Number: 14
8.Number: 15
9.Number: 16
10.Number: 17
11.Number: 18
12.Number: 19
13.Number: 2
14.Number: 20
15.Number: 21
16.Number: 22
17.Number: 23
18.Number: 24
19.Number: 25
20.Number: 26
21.Number: 27
22.Number: 28
23.Number: 29
24.Number: 3
25.Number: 30
26.Number: 31
27.Number: 32
28.Number: 33
29.Number: 34
30.Number: 35
31.Number: 36
32.Number: 37
33.Number: 38
34.Number: 39
35.Number: 4
36.Number: 40
37.Number: 41
38.Number: 42
39.Number: 43
40.Number: 44
41.Number: 45
42.Number: 46
43.Number: 47
44.Number: 48
45.Number: 49
46.Number: 5
47.Number: 50
48.Number: 51
49.Number: 52
50.Number: 53
51.Number: 54
52.Number: 55
53.Number: 56
54.Number: 57
55.Number: 58
56.Number: 59
57.Number: 6
58.Number: 60
59.Number: 61
60.Number: 62
61.Number: 63
62.Number: 64
63.Number: 65
64.Number: 66
65.Number: 67
66.Number: 68
67.Number: 69
68.Number: 7
69.Number: 70
70.Number: 71
71.Number: 72
72.Number: 73
73.Number: 74
74.Number: 75
75.Number: 76
76.Number: 77
77.Number: 78
78.Number: 79
79.Number: 8
80.Number: 80
81.Number: 81
82.Number: 82
83.Number: 83
84.Number: 84
85.Number: 85
86.Number: 86
87.Number: 87
88.Number: 88
89.Number: 89
90.Number: 9
91.Number: 90
92.Number: 91
93.Number: 92
94.Number: 93
95.Number: 94
96.Number: 95
97.Number: 96
98.Number: 97
99.Number: 98
100.Number: 99
Process finished with exit code 0
Since it is a queue of Strings it is sorted alphabetically. If you want to keep it as Strings, you can use a custom comparator that converts the Strings to ints and compares those:
// This constructor requires an initial capacity before the comparator
Queue<String> queue = new PriorityQueue<String>(100, new Comparator<String>() {
public int compare(String s1, String s2) {
return Integer.parseInt(s1) - Integer.parseInt(s2);
}
});
Another option is to change the type of the queue to Integer and convert the input:
Queue<Integer> queue = new PriorityQueue<Integer>();
...
while ((strLine = br.readLine()) != null) {
queue.offer(Integer.parseInt(strLine));
}

Printing data file containing multiple matrixes

I'm running into a problem with a program that I'm writing for a class.
I was given a text file that contains three matrices and I need to create a loop that prints out all three of them in the output through various filters.
Here is what the file contains:
15 15
91 114 75 145 149 250 31 103 88 123 27 120 187 140 52
108 23 43 126 51 9 107 29 20 221 18 41 178 245 159
187 53 7 107 96 82 70 2 171 2 36 84 135 187 92
176 30 199 230 178 61 48 211 208 143 178 207 79 196 217
26 6 117 170 4 245 63 93 108 44 163 19 6 220 131
7 210 228 154 213 96 102 254 63 34 25 215 168 23 207
131 254 198 215 164 6 141 150 147 26 242 199 237 131 240
102 22 248 74 26 3 138 145 132 120 97 126 8 86 166
178 68 73 127 56 180 182 152 3 149 184 42 204 9 172
104 203 99 132 204 137 33 69 140 19 131 38 239 56 180
163 249 88 222 98 150 58 155 115 188 70 189 162 33 1
113 141 52 196 139 241 68 37 89 215 166 7 200 179 26
21 68 167 53 226 167 193 232 133 79 212 163 101 157 233
122 17 114 224 129 247 35 84 120 51 91 149 127 150 19
217 253 145 45 205 179 107 76 214 48 230 218 8 135 25
6 6
201 159 87 63 240 244
231 32 222 76 5 255
10 5 248 139 47 64
167 76 138 177 107 159
188 122 154 165 205 22
222 149 148 85 129 57
5 5
201 159 87 63 240
231 32 222 76 5
10 5 248 139 47
167 76 138 177 107
188 122 154 165 205
I was able to get a loop that read the file and prints out the first 15x15 array, but I need a loop that will print out the other three after it including the filters applied to the data.
That is:
Base image data:
(15x15 array)
(6x6 array)
(5x5 array)
Filtered data:
(15x15 filtered)
(6x6 filtered)
(5x5 filtered)
I'm able to print out the first array just fine, but I am racking my brain trying to find a way to loop the code to print out the other two arrays. Additionally, I have a second problem that when the filtered data is printed, it's all 0s like so:
Base Image Data
91 114 75 145 149 250 31 103 88 123 27 120 187 140 52
108 23 43 126 51 9 107 29 20 221 18 41 178 245 159
187 53 7 107 96 82 70 2 171 2 36 84 135 187 92
176 30 199 230 178 61 48 211 208 143 178 207 79 196 217
26 6 117 170 4 245 63 93 108 44 163 19 6 220 131
7 210 228 154 213 96 102 254 63 34 25 215 168 23 207
131 254 198 215 164 6 141 150 147 26 242 199 237 131 240
102 22 248 74 26 3 138 145 132 120 97 126 8 86 166
178 68 73 127 56 180 182 152 3 149 184 42 204 9 172
104 203 99 132 204 137 33 69 140 19 131 38 239 56 180
163 249 88 222 98 150 58 155 115 188 70 189 162 33 1
113 141 52 196 139 241 68 37 89 215 166 7 200 179 26
21 68 167 53 226 167 193 232 133 79 212 163 101 157 233
122 17 114 224 129 247 35 84 120 51 91 149 127 150 19
217 253 145 45 205 179 107 76 214 48 230 218 8 135 25
Image Filter1:
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
The code I have it pretty extensive, so I'm having trouble pinpointing why it's returning 0s.
Here is my code:
public static void main(String[] args) throws IOException {
Scanner scanner = new Scanner(new File("imagedata.txt"));
int r = scanner.nextInt();
int c = scanner.nextInt();
int [][] imageData = new int[r][c];
//for loop to create 2d array from image data
for(int row=0; row<imageData.length; row++) {
for(int col=0; col<imageData[row].length; col++) {
imageData[row][col] = scanner.nextInt();
}
}
System.out.println("Base Image Data");
for(int[] row : imageData) {
for(int num : row) {
System.out.print(num+" ");
}
System.out.println();
}
System.out.println("Image Filter1:");
int[][] filter1 = applyFilter1(imageData);//call return from applyFilter1
for(int[] row : filter1){
for(int num : row){
System.out.print(num+" ");
}
System.out.println();
}
}
public static int[][] applyFilter1(int[][] imageData){
int[][] filtered = new int[imageData.length][imageData[0].length];
for (int row=0; row<filtered.length;row++){
for (int col=0;col<filtered[row].length;col++){
int[] nebs = getNeighbors(row, col, imageData);
int sum = 0;
for(int i=0; i<nebs.length; i++){
sum = sum + nebs[i];
int average = sum / nebs.length;
filtered[row][col] = average;
}
}
}
return filtered;
}
public static int[] getNeighbors(int row, int col, int[][] imageData){
//find neighbors of current index
int [][] copyImage = new int[imageData.length][imageData[0].length];
try{
for(int r=0; r<imageData.length; r++){
for(int c=0; c<imageData[r].length; c++){
imageData[r][c] = copyImage[r][c];
}
}
} catch(Exception e){
System.out.println("Array copy not successful");
}
//handles the top row of the array
if(row==0){//if copyImage[0].length
if(col==0){//handles upper left corner of array
int[] nebs = {copyImage[row][col], copyImage[row+1][col],
copyImage[row][col+1]};
return nebs;
}
else if(col==copyImage[row].length-1){//handles upper right corner of array
int[] nebs = {copyImage[row][col], copyImage[row][col-1],
copyImage[row+1][col]};
return nebs;
}
else{//handles top row of array between corners
int[] nebs = {copyImage[row][col], copyImage[row][col-1],
copyImage[row+1][col], copyImage[row][col+1]};
return nebs;
}
}
//handles the bottom row of the array
else if(row==copyImage.length-1){//if the row is at max value
if(col==0){//handles botton left corner of array
int[] nebs = {copyImage[row][col], copyImage[row-1][col],
copyImage[row][col+1]};
return nebs;
}
else if(col==copyImage[row].length-1){//handles bottom right corner of array
int[] nebs = {copyImage[row][col], copyImage[row-1][col],
copyImage[row][col-1]};
return nebs;
}
else{//handles bottom row of array
int[] nebs = {copyImage[row][col], copyImage[row-1][col],
copyImage[row][col-1], copyImage[row][col+1]};
return nebs;
}
}
//handles leftmost column of array
else if(col==0){//if col=0 and row increases
int[] nebs = {copyImage[row][col], copyImage[row-1][col],
copyImage[row+1][col], copyImage[row][col+1]};
return nebs;
}
//handles rightmost column of array
else if(col==copyImage[row].length-1){//if col=max value and row increases
int[] nebs = {copyImage[row][col], copyImage[row-1][col],
copyImage[row+1][col], copyImage[row][col-1]};
return nebs;
}
//handles values in the body of the array
else{
int[] nebs = {copyImage[row][col], copyImage[row-1][col],
copyImage[row+1][col], copyImage[row][col-1],
copyImage[row][col+1]};
return nebs;
}
}
I'm still new to java, despite the amount of code in this program. So any guidance and feedback is welcome.
You can simply read this file line-by-line, split each string into an array of numbers, then format them as a three-character string, concatenate them back and output. No matter how many matrices are in this file.
List<String> list = List.of(
"91 114 75 145 149 250 31 103 88 123 27 120 187 140 52",
"108 23 43 126 51 9 107 29 20 221 18 41 178 245 159",
"187 53 7 107 96 82 70 2 171 2 36 84 135 187 92");
list.stream()
.map(str -> Arrays
// split string into an array of numbers
.stream(str.split("\s+"))
// format as a three-character string
.map(s -> String.format("%3s", s))
// concatenate into a single string
.collect(Collectors.joining(" ")))
// output line by line
.forEach(System.out::println);
Output:
91 114 75 145 149 250 31 103 88 123 27 120 187 140 52
108 23 43 126 51 9 107 29 20 221 18 41 178 245 159
187 53 7 107 96 82 70 2 171 2 36 84 135 187 92

JOptionPane and Graphs

I would like to know how to give JOptionPane the ability to scroll through a histogram. I managed to get JOptionPane to display my histogram, the only problem is you can't scroll through it. The window stretches to the bottom of the screen and displays only half of the graph.
Note: This only happens when reading large input files that contain 300+ integers between 0 and 130. The program will not recognize anything else.
Input Values:
54
38
42
40
34
51
54
58
61
55
54
42
40
34
51
54
54
54
38
60
42
40
54
54
54
54
54
54
54
54
54
54
54
54
54
54
54
32
28
24
18
9
4
22
31
38
34
41
32
28
24
18
31
38
34
41
32
28
24
18
31
38
34
41
32
28
31
38
35
51
34
41
56
63
59
66
48
46
58
41
56
63
51
59
48
46
58
41
56
63
53
52
58
48
49
58
41
56
63
51
52
59
58
66
63
71
69
70
72
67
66
63
71
74
75
69
73
78
72
67
63
71
74
59
56
69
70
78
72
66
71
74
69
70
78
72
67
63
59
58
57
64
71
72
67
63
59
64
71
73
79
75
78
72
67
63
59
63
71
73
75
78
72
67
63
57
73
77
75
78
72
67
71
73
77
75
78
81
83
87
84
91
92
90
84
76
83
82
89
78
81
83
87
84
91
92
90
84
78
85
82
89
96
91
78
81
83
86
82
91
92
90
84
85
82
89
92
96
91
95
97
98
91
95
97
93
87
85
94
89
92
96
93
96
97
98
98
100
102
95
97
93
87
88
89
93
84
89
92
95
95
95
97
94
91
87
84
80
90
82
80
73
75
70
74
74
75
70
66
63
71
69
70
72
67
66
63
71
55
59
53
58
52
67
63
71
74
59
56
69
70
58
62
56
51
54
49
60
68
62
67
63
59
58
57
64
44
38
42
40
34
51
54
55
54
42
40
34
51
54
54
54
38
42
31
38
34
41
32
28
24
18
31
38
34
41
32
28
24
18
31
38
34
41
32
28
31
28
35
41
34
37
26
23
29
40
45
46
39
31
40
38
29
34
36
import javax.swing.*;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
public class CoolWeather
{
static JFileChooser selecter;
static Scanner in;
public static void main(String[] args) throws FileNotFoundException
{
//Get Input File
File inputFile;
selecter = new JFileChooser(".");
int status = selecter.showOpenDialog(null);
if(status != JFileChooser.APPROVE_OPTION)
{
JOptionPane.showMessageDialog(null, "Closing Program");
System.exit(0);
}
inputFile = selecter.getSelectedFile();
JOptionPane.showMessageDialog(null, "Opening: " + inputFile.getName());
//Creates Array
int[] temps = readData(inputFile);
//Prints Histogram
showMessage(temps);
}
//The Following Method Creates and Populates An Array With Data
//From The Input File
public static int[] readData(File inputFile) throws FileNotFoundException
{
in = new Scanner(inputFile);
in.useDelimiter("[^0-9/s]+");
int[] temps = new int[131];
int count = 0;
int num;
do
{
num = in.nextInt();
count++;
temps[num]++;
}
while (in.hasNextInt());
JOptionPane.showMessageDialog(null, "The Number Of Entries Read: " + count);
return temps;
}
public static void showMessage(int[] temps)
{
String output = "Temp\tCount\tVisual";
// for each array element, output a bar in histogram
for ( int counter = 0; counter < temps.length; counter++ )
{
if (temps[counter] > 0)
{
output += "\n" + counter + "\t" + temps[ counter ] + "\t";
// print bar of asterisks
for ( int stars = 0; stars < temps[ counter ]; stars++ )
{output += "*";}
}
} // end outer for
JTextArea outputArea = new JTextArea();
outputArea.setText( output );
JOptionPane.showMessageDialog( null, outputArea, "CoolWeather Histogram", JOptionPane.INFORMATION_MESSAGE );
System.exit( 0 );
}
}
This is the JOptionPane I use for UI when handling exceptions, but the principle is the same - JTextArea in JScrollPane
JLabel label = new JLabel(e.getLocalizedMessage() + ":");
label.setFont(getFont().deriveFont(Font.BOLD));
label.setAlignmentX(JLabel.LEFT_ALIGNMENT);
StringWriter writer = new StringWriter();
e.printStackTrace(new PrintWriter(writer));
JTextArea textArea = new JTextArea();
textArea.setEditable(false);
textArea.setFont(getFont());
textArea.setTabSize(2);
textArea.setText(writer.toString());
SwingUtilities.invokeLater(() -> textArea.setCaretPosition(0));
JScrollPane scrollPane = new JScrollPane(textArea);
scrollPane.setAlignmentX(JScrollPane.LEFT_ALIGNMENT);
scrollPane.setPreferredSize(new Dimension(500, 200));
JPanel panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.PAGE_AXIS));
panel.add(label);
panel.add(Box.createVerticalStrut(5));
panel.add(scrollPane);
JOptionPane.showMessageDialog(this, panel, ApplicationInfo.getAppName(), JOptionPane.ERROR_MESSAGE);
JTextArea outputArea = new JTextArea();
outputArea.setText(output);
outputArea.setEditable(false);
JScrollPane scrollPane = new JScrollPane(outputArea);
scrollPane.setAlignmentX(JScrollPane.LEFT_ALIGNMENT);
scrollPane.setPreferredSize(new Dimension(500, 200));
JOptionPane.showMessageDialog( null, scrollPane, "CoolWeather Histogram", JOptionPane.INFORMATION_MESSAGE);
System.exit( 0 );

Different conversion from BigIntger to byte[] if I use C# and Java

If have the following BigInteger:
1379080579050447841330186236235223160927998000398161138225875482305250883605652677639242794753995315199229112894647269426499088162253680340518114657361569012095908691691924534414360438924914998
If I convert to byte[] using ToByteArray in C# I get a result but if I convert the same BigInteger in Java I get a different result. How can I reach the same result? I need the byte[] since I need to remove the padding and then transform the byte array resulting into a string
As pointed out in the comments, the reason you're seeing different values between the byte[] from the C# BigInteger and the Java BigInteger is that the byte order is reversed: C# is little-endian and Java is big-endian.
(See Java vs. C#: BigInteger hex string yields different result? for more details).
As you can see, the order of the bytes in the array is exactly reversed:
C#
BigInteger bi = BigInteger.Parse("1379080579050447841330186236235223160927998000398161138225875482305250883605652677639242794753995315199229112894647269426499088162253680340518114657361569012095908691691924534414360438924914998");
byte[] ba = bi.ToByteArray();
for (int i = 0; i < ba.Length; i++) {
Console.Write(ba[i] + " ");
}
// 54 49 48 50 47 52 48 47 49 50 32 111 110 114 111 105 103 32 44 98 117 108 67
// 32 97 116 105 118 69 32 44 101 108 97 117 113 115 97 80 32 101 110 111 105 108
// 103 101 86 32 111 116 110 101 118 69 32 44 52 57 57 49 47 56 48 47 49 50 32 44
// 105 115 115 111 82 32 111 99 114 97 77
Java
BigInteger bi = new BigInteger("1379080579050447841330186236235223160927998000398161138225875482305250883605652677639242794753995315199229112894647269426499088162253680340518114657361569012095908691691924534414360438924914998");
byte[] ba = bi.toByteArray();
for (int i = 0; i < ba.length; i++) {
System.out.print(ba[i] + " ");
}
// 77 97 114 99 111 32 82 111 115 115 105 44 32 50 49 47 48 56 47 49 57 57 52 44
// 32 69 118 101 110 116 111 32 86 101 103 108 105 111 110 101 32 80 97 115 113 117
// 97 108 101 44 32 69 118 105 116 97 32 67 108 117 98 44 32 103 105 111 114 110 111
// 32 50 49 47 48 52 47 50 48 49 54
If you want a Java byte[] to hold the bytes in the same order as C#, you will need to reverse its contents.
You can just write a simple helper method that reverses the order of the bytes in the array:
public static void reverse(byte[] array) {
for (int i = 0, j = array.length - 1; i < j; i++, j--) {
byte b = array[i];
array[i] = array[j];
array[j] = b;
}
}
Or if you have access to 3rd-party libraries, you can use org.apache.commons.lang3.ArrayUtils.reverse(byte[]).
That would give you a byte[] in Java holding the bytes in the same order as C#:
Java
BigInteger bi = new BigInteger("1379080579050447841330186236235223160927998000398161138225875482305250883605652677639242794753995315199229112894647269426499088162253680340518114657361569012095908691691924534414360438924914998");
byte[] ba = bi.toByteArray();
reverse(ba);
for (int i = 0; i < ba.length; i++) {
System.out.print(ba[i] + " ");
}
// 54 49 48 50 47 52 48 47 49 50 32 111 110 114 111 105 103 32 44 98 117 108 67
// 32 97 116 105 118 69 32 44 101 108 97 117 113 115 97 80 32 101 110 111 105 108
// 103 101 86 32 111 116 110 101 118 69 32 44 52 57 57 49 47 56 48 47 49 50 32 44
// 105 115 115 111 82 32 111 99 114 97 77

String to Int 2D array

How do you fix the problem of
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 19 at ProjectEuler11.main(ProjectEuler11.java:21).
Because what I am trying to do is to put all numbers to int 2D array from this String
class ProjectEuler11 {
public static void main(String []args) {
String digitNumber = "08 02 22 97 38 15 00 40 00 75 04 05 07 78 52 12 50 77 91 08 49 49 99 40 17 81 18 57 60 87 17 40 98 43 69 48 04 56 62 00 81 49 31 73 55 79 14 29 93 71 40 67 53 88 30 03 49 13 36 65 52 70 95 23 04 60 11 42 69 24 68 56 01 32 56 71 37 02 36 91 22 31 16 71 51 67 63 89 41 92 36 54 22 40 40 28 66 33 13 80 24 47 32 60 99 03 45 02 44 75 33 53 78 36 84 20 35 17 12 50 32 98 81 28 64 23 67 10 26 38 40 67 59 54 70 66 18 38 64 70 67 26 20 68 02 62 12 20 95 63 94 39 63 08 40 91 66 49 94 2124 55 58 05 66 73 99 26 97 17 78 78 96 83 14 88 34 89 63 72 21 36 23 09 75 00 76 44 20 45 35 14 00 61 33 97 34 31 33 95 78 17 53 28 22 75 31 67 15 94 03 80 04 62 16 14 09 53 56 92 16 39 05 42 96 35 31 47 55 58 88 24 00 17 54 24 36 29 85 57 86 56 00 48 35 71 89 07 05 44 44 37 44 60 21 58 51 54 17 58 19 80 81 68 05 94 47 69 28 73 92 13 86 52 17 77 04 89 55 40 04 52 08 83 97 35 99 16 07 97 57 32 16 26 26 79 33 27 98 66 88 36 68 87 57 62 20 72 03 46 33 67 46 55 12 32 63 93 53 69 04 42 16 73 38 25 39 11 24 94 72 18 08 46 29 32 40 62 76 36 20 69 36 41 72 30 23 88 34 62 99 69 82 67 59 85 74 04 36 16 20 73 35 29 78 31 90 01 74 31 49 71 48 86 81 16 23 57 05 54 01 70 54 71 83 51 54 69 16 92 33 48 61 43 52 01 89 19 67 48";
String []numberVector = digitNumber.split(" ");
int [][]digitNumberVector = new int[19][19];
int x = 0;
int y = 0;
int answerNumber = 0;
for(int parameter2 = 0; parameter2 < 20; parameter2++) {
for(int parameter3 = 0; parameter3 < 20; parameter3++){
for(String parameter : numberVector) {
x = parameter2;
y = parameter3;
digitNumberVector[x][y] = Integer.parseInt(parameter);
}
}
}
}
}// Java Document
new int[19][19]
In such array, elements are indexed 0...18. But in your for loops:
for(int parameter2 = 0; parameter2 < 20; parameter2++)
parameter2 and parameter3 take values 0...19, and this 19 is already out of bounds.
uchitha Kiripitige is correct, the array is indexed wrong. Below is a correct version of your code that dynamically calculates the indices. Also, I made a few performance optimizations to your code.
public class ProjectEuler11 {
public static void main(String []args){
String digitNumber = "08 02 22 97 38 15 00 40 00 75 04 05 07 78 52 12 50 77 91 08 49 49 99 40 17 81 18 57 60 87 17 40 98 43 69 48 04 56 62 00 81 49 31 73 55 79 14 29 93 71 40 67 53 88 30 03 49 13 36 65 52 70 95 23 04 60 11 42 69 24 68 56 01 32 56 71 37 02 36 91 22 31 16 71 51 67 63 89 41 92 36 54 22 40 40 28 66 33 13 80 24 47 32 60 99 03 45 02 44 75 33 53 78 36 84 20 35 17 12 50 32 98 81 28 64 23 67 10 26 38 40 67 59 54 70 66 18 38 64 70 67 26 20 68 02 62 12 20 95 63 94 39 63 08 40 91 66 49 94 2124 55 58 05 66 73 99 26 97 17 78 78 96 83 14 88 34 89 63 72 21 36 23 09 75 00 76 44 20 45 35 14 00 61 33 97 34 31 33 95 78 17 53 28 22 75 31 67 15 94 03 80 04 62 16 14 09 53 56 92 16 39 05 42 96 35 31 47 55 58 88 24 00 17 54 24 36 29 85 57 86 56 00 48 35 71 89 07 05 44 44 37 44 60 21 58 51 54 17 58 19 80 81 68 05 94 47 69 28 73 92 13 86 52 17 77 04 89 55 40 04 52 08 83 97 35 99 16 07 97 57 32 16 26 26 79 33 27 98 66 88 36 68 87 57 62 20 72 03 46 33 67 46 55 12 32 63 93 53 69 04 42 16 73 38 25 39 11 24 94 72 18 08 46 29 32 40 62 76 36 20 69 36 41 72 30 23 88 34 62 99 69 82 67 59 85 74 04 36 16 20 73 35 29 78 31 90 01 74 31 49 71 48 86 81 16 23 57 05 54 01 70 54 71 83 51 54 69 16 92 33 48 61 43 52 01 89 19 67 48 76";
String []numberVector = digitNumber.split(" ");
final int DIM = (int)Math.sqrt(numberVector.length + 1);
int [][]digitNumberVector = new int[DIM][DIM];
int vectorIdx = 0;
for(int parameter2 = 0; parameter2 < DIM; parameter2++){
for(int parameter3 = 0; parameter3 < DIM; parameter3++){
digitNumberVector[parameter2][parameter3] = Integer.parseInt(numberVector[vectorIdx]);
vectorIdx++;
}
}
}
}// Java Document
As a side note, your digitNumber string only contained 399 values instead of 400 so I had to add an extra integer so the equal-sized for loops would work properly.

Categories