I am getting a nullPointerException trying to add values from a text file to a 2d array. The first 2 values determine the rows and columns. Any ideas what is throwing it. Ignore the exception handling, and the print statements. I am trying to get the array initialized then will go back and beef it up a bit.
public Help(String filename) throws FileNotFoundException,
InvalidFileFormatException {
this.filename = filename;
System.out.println("Reading in file: " + filename);
String number = "";
int row = 0;
int col = 0;
int count = 0;
try {
Scanner inputFile = new Scanner(new File(filename));
while (inputFile.hasNextInt()) {
row = Integer.parseInt(inputFile.next());
col = Integer.parseInt(inputFile.next());
System.out.println("Row : " + row);
System.out.println("Col : " + col);
baseMap = new double[row][col];
System.out.println(baseMap[2][4]);
for (int i = 0; i < baseMap.length; i++){
for (int j = 0; j < baseMap[i].length; j++){
baseMap[i][j] = Double.parseDouble(inputFile.next());
}
}
}
System.out.println(baseMap[2][4]);
} catch (Exception e) {
System.out.println(e.toString());
}
OUTPUT
Reading in file: sampleMap2.txt
Row : 5
Col : 5
0.0
Exception in thread "main" java.lang.NullPointerException
What value do you expect to see here;
baseMap = new double[row][col];
System.out.println(baseMap[2][4]);
How about if row == 1?
Also what if there is no more data at:
baseMap[i][j] = Double.parseDouble(inputFile.next());
Maybe you just don't have enough data.
Related
Hi I am new on programing and I am having a problem I am trying to copy some things from a file to a array
and I just want to copy in the position 1,2,3 and 4 from the file. Example copy to the array 11 , G , 0 , 20.
FILE TEXT:
0;11;G;0;200;1
2;10;F;0;300;2
0;12;J;0;100;3
String[][] aa = new String[100][6];
try {
Scanner x = new Scanner(new File("Turmas.txt"));
x.useDelimiter("[;\n]");
for (int i = 0; i < 100; i++) {
for (int j = 0; j < 6; j++) {
if (x.hasNext()) {
aa[i][j] = x.next();
}
}
}
x.close();
} catch (FileNotFoundException ex) {
JOptionPane.showMessageDialog(
null, "An error occurred, try restarting the program!",
"ERROR!", JOptionPane.ERROR_MESSAGE
);
}
String[][] aaa = new String[100][4];
for (int i = 0; i < 100; i++) {
for (int j = 0; j < 4; j++) {
if (aa[i][j] == null) {
System.out.println("null " + i + " " + j);
}
else {
if (aa[i][0].equals(String.valueOf(SAVEID))) {
aaa[i][j] = aa[i][1];
aaa[i][j + 1] = aa[i][2];
aaa[i][j + 2] = aa[i][3];
aaa[i][j + 3] = aa[i][4];
}
}
}
}
System.out.println(aaa[0][0]);
System.out.println(aaa[0][1]);
System.out.println(aaa[0][2]);
System.out.println(aaa[0][3]);
If only 4 values are needed from the input array are needed, why not just read these specific values?
String[] result = new String[4];
try (Scanner input = new Scanner(new File("Turmas.txt")) // input closed automatically
.useDelimiter(";|\\R") // use character class \R to match line-feed characters
) {
if (input.hasNext()) {
input.next(); // skip the 1st token
for (int i = 0; i < result.length && input.hasNext(); i++) {
result[i] = input.next();
}
}
} catch (FileNotFoundException ex) {
JOptionPane.showMessageDialog(
null, "An error occurred, try restarting the program!",
"ERROR!", JOptionPane.ERROR_MESSAGE
);
}
If it is needed to read the columns with indexes [1..4] from the file containing 6 columns per line, it is cleaner to read the source file line by line, split each line by ;, skip 1 column with index 0, and keep the 4 columns.
String[][] result = new String[100][4];
try (Scanner input = new Scanner(new File("Turmas.txt"))) {
for (int i = 0; i < result.length && input.hasNextLine(); i++) {
String[] parts = input.nextLine().split(";");
for (int j = 1; j < Math.min(result[i].length, parts.length); j++) {
result[i][j - 1] = parts[j];
}
}
} catch (FileNotFoundException ex) {
JOptionPane.showMessageDialog(
null, "An error occurred, try restarting the program!",
"ERROR!", JOptionPane.ERROR_MESSAGE
);
}
This loop:
for(int j=0;j<4;j++)
runs again with a value of j = 1 after it completes the first iteration, so when it gets to the expression aaa[i][j+3] the second index evaluates to 4, which of course is illegal. I'm not sure why you used a for loop there, since you manually increment the index values as you assign the aaa values?
I have a text file that I have to store into a 2d array, with 3 columns, and numRecords rows, but is implemented within a method. The parameter numRecords is the number of values to read from the input file. I'm getting an InputMismatchException and I can't figure out why. Any help would be greatly appreciated
public String[][] readFile(File file, int numRecords) throws IOException {
int numRows = numRecords;
int numColumns = 3; // column 1 will be age, column 2 will be height, column 3 will be weight
String[][] data = new String[numRows][numColumns];
try {
Scanner readFile = new Scanner(file);
String line = null;
line = readFile.nextLine().trim();
while (readFile.hasNextLine()) {
line = readFile.nextLine();
String[] str = line.split(",");
for (String element : str) {
element = element + " ";
for (int row = 0; row < data.length; row++) {
for (int column = 0; column < data[0].length; column++) {
data[row][column] = Integer.toString(readFile.nextInt());
data[row][column] = Integer.toString(readFile.nextInt());
data[row][column] = Integer.toString(readFile.nextInt());
}
}
}
}
readFile.close();
}
catch (InputMismatchException e1) {
e1.printStackTrace();
}
return data;
}
You are generating element(s) from your scanner by reading line(s). You are also attempting to then read int(s) from the scanner and ignoring the elements you have read. Another possible issue is your code doesn't test that the file can actually be read before starting. And I would prefer try-with-Resources over explicitly closing the Scanner (as here you leak a file handle whenever there is an exception). Also, why read int(s) and convert them to a String - I would prefer reading into an int[][]. Putting that all together,
public int[][] readFile(File file, int numRows) throws IOException {
if (!file.exists() || !file.canRead()) {
System.err.printf("Cannot find file: %s%n", file.getCanonicalPath());
return null;
}
int numColumns = 3;
int[][] data = new int[numRows][numColumns];
try (Scanner readFile = new Scanner(file)) {
while (readFile.hasNextLine()) {
String line = readFile.nextLine();
String[] tokens = line.split(",");
int row = 0, column = 0;
for (String element : tokens) {
if (column >= numColumns) {
column = 0;
row++;
}
data[row][column] = Integer.parseInt(element);
column++;
}
}
} catch (InputMismatchException e1) {
e1.printStackTrace();
}
return data;
}
i have file txt in desktop :
1 5 23
2 5 25
3 30 36
i want sum column by column 1 + 2 + 3 =... and 5 + 5...n and 23,...n
Scanner sc = new Scanner (file("patch");
while (sc.hasNextLine)
{
//each sum by column
}
help me please thanks
I would use a try-with-resources to clean up my Scanner using the File. Also, you could construct a Scanner around the line of input to get your int columns (that doesn't need to be closed because String(s) aren't closable anyway). Something like,
try (Scanner sc = new Scanner(new File("patch"))) {
while (sc.hasNextLine()) {
String line = sc.nextLine();
Scanner row = new Scanner(line);
long sum = 0;
int count = 0;
while (row.hasNextInt()) {
int val = row.nextInt();
if (count == 0) {
System.out.print(val);
} else {
System.out.printf(" + %d", val);
}
sum += val;
count++;
}
System.out.println(" = " + sum);
}
} catch (IOException e) {
e.printStackTrace();
}
As the Scanner(String) Constructor Javadoc documents
Constructs a new Scanner that produces values scanned from the specified string.
Edit To sum the columns is a little trickier, but you could read everything into a multidimensional List<List<Integer>> like
try (Scanner sc = new Scanner(new File("patch"))) {
List<List<Integer>> rows = new ArrayList<>();
int colCount = 0;
while (sc.hasNextLine()) {
List<Integer> al = new ArrayList<>();
String line = sc.nextLine();
Scanner row = new Scanner(line);
colCount = 0;
while (row.hasNextInt()) {
colCount++;
int val = row.nextInt();
al.add(val);
}
rows.add(al);
}
for (int i = 0; i < colCount; i++) {
long sum = 0;
for (List<Integer> row : rows) {
sum += row.get(i);
}
if (i != 0) {
System.out.print("\t");
}
System.out.print(sum);
}
System.out.println();
} catch (IOException e) {
e.printStackTrace();
}
Edit 2 For efficiencies sake, you might prefer to use a Map like
try (Scanner sc = new Scanner(new File("patch"))) {
Map<Integer, Integer> cols = new HashMap<>();
while (sc.hasNextLine()) {
String line = sc.nextLine();
Scanner row = new Scanner(line);
int colCount = 0;
while (row.hasNextInt()) {
int val = row.nextInt();
if (cols.containsKey(colCount)) {
val += cols.get(colCount);
}
cols.put(colCount, val);
colCount++;
}
}
for (int i : cols.values()) {
System.out.printf("%d\t", i);
}
System.out.println();
} catch (IOException e) {
e.printStackTrace();
}
Please find the code. Please go through the comments.
This is one way of doing for your reference. I want you to try other ways to improve your knowledge rather just using this code.
int sums[] = null;
while (sc.hasNextLine())
{
String row = sc.next();// get first row
String[] values = row.split(" ");// split by space
if(null == sums)
{
sums = new int[values.length];// create sum array with first row size
}
int index = 0;
for (String value : values)
{
sums[index] = sums[index]+Integer.parseInt(value);//adding current row value to current sum
index++;
}
}
if(null != sums)
{
int index=0;
for (int sum : sums)
{
System.out.println("Sum of column "+index+" : "+sum);// Printing each column sum
index++;
}
}
If your file is CSV formatted, then split line by comma(",") and find number of columns based on split array length.
Like below:
String line = sc.next();
String[] lineArr = line.split(",");
int len = lineArr.length;
create array of arraylists of size len and store each column field in the respective arraylist.
finally, at the end apply sum on each arraylist to calculate sum of each column values.
Hi I am new to 2D arrays and I am having problems with showing the content of the array indexes. I am reading the values from a text file and storing them into a 2D array. I am not sure if the items are even storing properly. When I use a System.println() during the iteration of the 2D array being filled then it prints all the values out as they currently show up. However if I try filling the array and call any location index after such as data[45][45]; it will only return a 0. Each int value taken from the text file that should be stored are each in the millions.
final String FILENAME = "DATA.TXT";
int [ ][ ] data = null;
int numberOfRows = 0;
int numberOfCols = 0;
String message ="";
try {
File file = new File(FILENAME);
Scanner inputFile = new Scanner(file);
// Read the number of Rows and Columns first
numberOfRows = inputFile.nextInt();
numberOfCols = inputFile.nextInt();
//Creates the row and column amount
data = new int[numberOfRows][numberOfCols];
for(int i = 0; i < data.length; i++)
{
for(int j = 0; j < data[5].length; j++)
{
while(inputFile.hasNextInt())
{
data[i][j] = inputFile.nextInt();
//System.out.println(data[i][j]); //This works for displaying the values cuurently
}
}
}
inputFile.close();
}
catch (FileNotFoundException ex)
{
System.out.println("Error reading data from " + FILENAME +
" Exception = " + ex.getMessage());
}
System.out.println("Data has been read - file has " + numberOfRows +
" rows and " + numberOfCols + " columns.");
//THIS or even using a loop to iterate through the 2D array that should contain
// the values does not appear and only ends up as 0 as if the values are not stored.
System.out.print(data[56][56]);
}
}
I have looked at this for a few hours and I do not understand if the values are not being stored properly or if there is a reason I cannot call the value in any index of data such as data[45][45] or using a loop such as
for(int n =0; n <data.length; n++)
{
for(int k = 0; k < data[0].length; k++)
{
System.out.print(data[n][k]);
}
}
If I am doing this completely wrong or there is a much more efficient way to do this please let me know. Otherwise in general I do not know what is wrong.
Thank you for checking out my post and I believe this would be helpful to many new programmers to 2D arrays and file read.
FILE CONTENTS
500 1000
1052662 1025260 1064342 1045596 1093363 1063663 1014129 1070544 1005352 1046317 1059536 1009817 1049327 1012134 1047499 1026392 1056558 1098823 1060554 1028017 1046977 1022098 1018538 1077771 1082687 1025653 1056869 1076473 1097420 1080444 1063797 1014295 1083251 1037760 1026325 1003914 1034680 1069524 1029877 1075546 1047177 1061381 1080359 1035442
Try this :
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
final String FILENAME = "d:/data.txt";
long[][] data=null;
int numberOfRows = 0;
int numberOfCols = 0;
String message = "";
try {
File file = new File(FILENAME);
Scanner inputFile = new Scanner(file);
// Read the number of Rows and Columns first
numberOfRows = inputFile.nextInt();
numberOfCols = inputFile.nextInt();
// Creates the row and column amount
data = new long[numberOfRows][numberOfCols];
for (int i = 0; i < numberOfRows; i++) {
for (int j = 0; j < numberOfCols; j++) {
data[i][j] = inputFile.nextInt();
}
}
inputFile.close();
} catch (FileNotFoundException ex) {
System.out.println("Error reading data from " + FILENAME
+ " Exception = " + ex.getMessage());
}
System.out.println("Data has been read - file has " + numberOfRows
+ " rows and " + numberOfCols + " columns.");
// display 2D array
for(int n =0; n <numberOfRows; n++)
{
for(int k = 0; k < numberOfCols; k++)
{
System.out.print(data[n][k] +" ");
}
System.out.println();
}
}
}
Found out I just had to get rid of the while statement and it seems to work perfectly. Thanks for all your help tho.
Hi I am reading Excel file from java using jxl workbook library.Below is the code.
Workbook wb = Workbook.getWorkbook(new File(destFile));
String line = ""; // available
for (int sheetNo = 0; sheetNo < wb.getNumberOfSheets(); sheetNo++) {
Sheet sheet = wb.getSheet(sheetNo);
System.out.println("Sheet Name is:\t" + sheet.getName());
if(sheet.getName().trim().equals("Store List")){
int columns = sheet.getColumns();
int rows = sheet.getRows();
String data;
for (int row = 0; row < rows; row++) {
for (int col = 1; col < columns; col++) {
data = sheet.getCell(col, row).getContents();
line = line + data + "#";
}
line += "#&#";
}
System.out.println("Entire line is" + line);
}
}
The above code reads row&column data from the excel file and passes it to the service method for further processing.
When I traverse it line-by-line for the empty cell, the Java code throws IndexOutOfBoundException. Please find the java code below which throws exception.
for(int elementCount=4;elementCount<elements.length;elementCount++) {
String strquantity = rowValues[elementCount];
int quantity=0;
if(strquantity.equals("")){
quantity = 0;
} else {
quantity = Integer.parseInt(strquantity);
System.out.println("Quantity value is:\t" + quantity);
}
}
As you the above code exception is thrown at line 2.
I believe that cause is due to workbook library.
After doing some rnd i got the solution,If it is empty cell will get the 0 or null value from jxl API.
As in my code i was looking for empty string
if(strquantity.equals("")){
quantity = 0;
}
now the code changed to below one
if(strquantity.equals(null) || strquantity.equals("0")){
quantity = 0;
}