How to assign value to two dimensional array? - java

I am newbie to Java so if my question doesn't make sense then please suggest to improve it so that I get my question answered.
This is how, I am initializing arrays.
public static String[][] data = null;
String[] ReadValue= new String[3];
int p = 0;
I am reading element of CSV file and trying to put in a JTable. Below is code to feed to two dimensional array from CSV file. It throws NullPointerException error when I try to assign value to two dimensional array.
In Line - data[p][i] = ReadValue[i].trim();
My code:
br = new BufferedReader(new FileReader(csvFile));
while ((line = br.readLine())!= null) {
ReadValue= line.split(csvSplitBy);
for (int i = 0; i < ReadValue.length; i++){
data[p][i] = ReadValue[i].trim();
// System.out.println(""+ReadValue[i].toString());
}
p++;
}
Error:
java.lang.NullPointerException
at com.srinar.graphicsTest.JtableTest.LoadCSVdata(JtableTest.java:82)
JtableTest.java:82 : - data[p][i] = ReadValue[i].trim();

You must initialize your array by choosing the number of rows and columns you wish to store in it.
For example :
public static String[][] data = new String[rowNum][colNum];

Related

String[] not adding to list correctly [duplicate]

This question already has answers here:
Why does my ArrayList contain N copies of the last item added to the list?
(5 answers)
Closed 6 years ago.
Okay so I have this two Lists called idadults and adults, I also have two String[] arrays called infoAdults (of size 255) and adultsID (of size 1). The code I have makes infoAdults read the information from a CSV file and adds that information to the adults list. It also checks if any value/box is missing, and changes its value to "9999". On column #15 in the CSV file, there's the id of each Adult, but some of them are missing. adultsID grabs each value of the column and then adds it to the idadults list. The code also first checks if that value exists, and if not it changes it to "9999" again.
My problem is that when I print the adults list it prints everything correctly like it should be, but when I try to print the idadults list it only prints the last value in the column over and over again n times, n being the size of the column. I already tried removing the "static" part when I define both of my Lists, but it didn't work. I also already tried to print adultsID[0] individually, and they all print correctly.
What do?
public String[] adultsID = new String[1];
public static List<String[]> idadults = new ArrayList<String[]>();
public static String csvFile = userDir + "/Adults.csv";
public String[] infoAdults = new String[255];
public static List<String[]> adults = new ArrayList<String[]>();
try {
br = new BufferedReader(new FileReader(csvFile));
while ((line = br.readLine()) != null) {
infoAdults = line.split(csvSplitBy);
for(int i=0;i<infoAdults.length;i++){
if(infoAdults[i].isEmpty()){
infoAdults[i]="9999";
}
if(i>16){
adultsID[0]=infoAdults[16];
}
else{
adultsID[0]="9999";
}
}
idadults.add(adultsID);
adults.add(infoAdults);
}
for (String[] strings : idadults) {
System.out.println(Arrays.toString(strings));
}
}
When you add adultsID to adults, you are adding the reference of adultsID.
Inside the while loop you are modifying only the data referenced by adultsID:
if(i>16){
adultsID[0]=infoAdults[16];
}
else{
adultsID[0]="9999";
}
And then you are adding the same reference to adults, on every iteration
idadults.add(adultsID);
So all the references point to same data which is modified every time the loop runs.
That is why you see only the last value reflected in all the list elements.
But for infoAdults , you are reassigning a new array to infoAdults everytime in the loop:
infoAdults = line.split(csvSplitBy);
So infoAdults refers to new data on every iteration.
Thus you add a new instance of infoAdults everytime in the list and all of them refer to different data
To get the expected output you can assign a new array to adultsID everytime in loop:
while ((line = br.readLine()) != null) {
infoAdults = line.split(csvSplitBy);
adultsID = new String[500];
for(int i=0;i<infoAdults.length;i++){
if(infoAdults[i].isEmpty()){
infoAdults[i]="9999";
}
if(i>16){
adultsID[0]=infoAdults[16];
}
else{
adultsID[0]="9999";
}
}

Having difficulty adding elements to 2-dimensional array

I have a .txt file that looks like this:
Mathematics:MTH105
Science:SCI205
Computer Science:CPS301
...
And I have an assignment that requires that I read file and place each line into an array that should look like this:
subjectsArray[][] = {
{"Mathematics", "MTH105"},
{"Science", "SCI205"},
{"Computer Science", "CPS301"}
};
I am getting a compile error when I attempt to add the contents of the file to a 2-dimensional array:
private static String[][] getFileContents(File file) {
Scanner scanner = null;
ArrayList<String[][]> subjectsArray = new ArrayList<String[][]>();
//Place the contents of the file in an array and return the array
try {
scanner = new Scanner(file);
int i = 0;
while(scanner.hasNextLine()) {
String line = scanner.nextLine();
String[] lineSplit = line.split(":");
for(int j = 0; j < lineSplit.length; j++) {
subjectsArray[i][j].add(lineSplit[0]); //The type of the expression must be an array type but it resolved to ArrayList<String[][]>
}
i++;
}
return subjectsArray;
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
scanner.close();
}
return null;
}
Error reads:
The type of the expression must be an array type but it resolved to ArrayList<String[][]>
I am new to multi-dimensional arrays and not sure what it is I'm doing wrong. Can someone tell me what I'm doing wrong?
Your first mistake is the selection of the type for the result: this type
ArrayList<String[][]>
represents a three-dimensional structure - a list of 2D arrays. What you need is a two-dimensional structure, e.g.
ArrayList<String[]>
So the first fix is this:
List<String[]> subjectsArray = new ArrayList<String[]>(); // Note the type on the left: it's an interface
Once this is done, the rest of the code flows by itself: you do not need the inner for loop, it gets replaced by a single line:
subjectsArray.add(lineSplit);
The final fix is the return line: you need to convert the List<String[]> to String[][], which can be done by calling toArray(), like this:
return subjectsArray.toArray(new String[subjectsArray.size()][]);
I think you are trying to use an ArrayList method on a String. I am not sure that is possible. The simplest way to do what you need I think is:
for(int j = 0; j < lineSplit.length; j++) {
subjectsArray[i][j]=lineSplit[j];
}

How to only get the lines you want from an arraylist depending on how they start, IN JAVA

I have a very long string containing GPS data but this is not important. What I need to do is separate the string which is in an arraylist (one big string) into multiple pieces.
The tricky part is that the string is made up of multiple 'gps sentances' and I only require two types of these sentences.
The types I need start with $GPSGSV and $GPSGGA. Basically I need to dump ONLY THESE sentences into another arraylist while leaving all the rest behind.
The new arraylist must be in line-by-line form so that each sentence is followed by a new line.
Each sentence also ends in one white space which could be helpful when splitting up. The arraylist data is shown below. - This is printed from the arraylist.
[$GPGSA,A,3,28,09,26,15,08,05,21,24,07,,,,1.6,1.0,1.3*3A,
$GPRMC,151018.000,A,5225.9627,N,00401.1624,W,0.11,104.71,210214,,*14,
$GPGGA,151019.000,5225.9627,N,00401.1624,W,1,09,1.0,38.9,M,51.1,M,,0000*72,
$GPGSA,A,3,28,09,26,15,08,05,21,24,07,,,,1.6,1.0,1.3*3A,
$GPGSV,3,1,12,26,80,302,44,09,55,063,40,05,53,191,39,08,51,059,37*79,
$GPGSV,3,2,12,28,43,112,34,15,40,284,42,21,18,305,33,07,18,057,27*7E,
$GPGSV,3,3,12,10,05,153,,24,05,234,38,18,05,318,22,19,05,035,*79,
$GPRMC,151019.000,A,5225.9627,N,00401.1624,W,0.10,105.97,210214,,*1D,
$GPGGA,151020.000,5225.9627,N,00401.1624,W,1,09,1.0,38.9,M,51.1,M,,0000*78,
$GPGSA,A,3,28,09,26,15,08,05,21,24,07,,,,1.6,1.0,1.3*3A,
$GPRMC,151020.000,A,5225.9627,N,00401.1624,W,0.12,105.18,210214,,*12,
$GPGSA,A,3,28,09,26,15,08,05,21,24,07,,,,1.6,1.0,1.3*3A,
$GPRMC,151021.000,A,5225.9626,N,00401.1624,W,0.11,99.26,210214,,*28,
$GPGGA,151022.000,5225.9626,N,00401.1623,W,1,09,1.0,38.9,M,51.1,M,,0000*7C,
$GPGSA,A,3,28,09,26,15,08,05,21,24,07,,,,1.6,1.0,1.3*3A,
$GPRMC,151022.000,A,5225.9626,N,00401.1623,W,0.11,109.69,210214,,*1F,
The data continues up to 2000 sentences.
Any help would be great. Thanks
EDITS ------
Looking back at what I have.. It may be best if I just read in the lines (as the file is formatted to be one sentence per line) which start with either the GSV or the GGA tag. In the buffered reader section of the method, how could I go about doing that? Here is some of my code ....
try {
File gpsioFile = new File(gpsFile);
FileReader file = new FileReader(gpsFile);
BufferedReader buffer = new BufferedReader(file);
StringBuffer stringbuff = new StringBuffer();
String ans;
while ((ans = buffer.readLine()) != null) {
gps.add(ans);
stringbuff.append(ans);
stringbuff.append("\n");
}
} catch (Exception e) {
e.printStackTrace();
}
From this could I get an Arraylist with just the GGA and GSV sentences/lines but in the same order that they were from the file?
Thanks
OK, I'd first start by splitting your string into individual lines with spilt():
String[] split = "$GPGSA,A,3,28,09,26,15,08,05,21,24,07,,,,1.6,1.0,1.3*3A,".split(",");
you can also use "\n" as a split delimiter instead of ",". This will give you an array over which you can iterate.
List<String> filtered = new ArrayList<String>()
for (String item, split) {
if (item.startsWith("$GPGSA")) {
filtered.add(item);
}
}
filtered would be a new Array with the items you want to keep.
This approach works with JDK 6+. In JDK 8, this kind of problem can be solved more elegantly with the stream API.
My understanding is that you've got an ArrayList with a single String element. That String is a comma separated list of values. So step one is to extract the string and split it into it's constituent parts. Once you've done that you can process the each item in turn.
private static List<List<String>> splitData(final ArrayList<String> data) {
final List<List<String>> filteredData = new ArrayList<List<String>>();
String fullText = data.get(0);
String[] splitData = fullText.split(",");
List<String> currentList = null;
for (int i = 0;i < splitData.length; i++) {
final String next = splitData[i];
if (startTags.contains(next)) {
if (interestingStartTags.contains(next)) {
currentList = new ArrayList<String>();
filteredData.add(currentList);
} else {
currentList = null;
}
}
if (currentList != null) {
currentList.add(next);
}
}
return filteredData;
}
The two static Set<String> provide the set of all 'gps sentence' start tags and also the set of ones you're interested in. The split data method uses startTags to determine if it has reached the start of a new sentence. If the new tag is also interesting, then a new list is created and added to the List<List<String>>. It is this list of lists that is returned.
If you don't know all of the strings you want to use as 'startTag' then you could next.startsWith("$GP") or similar.
Reading the file
Looking at the updated question of how to read the file you could remove the StringBuffer and instead simply add each line you read to an ArrayList. The code below will step over any lines that do not start with the two tags you are interested in. The order of the lines within lineList will match the order they are found in the file.
FileReader file = new FileReader(gpsFile);
BufferedReader buffer = new BufferedReader(file);
String ans;
ArrayList<String> lineList = new ArrayList<String>();
while ((ans = buffer.readLine()) != null) {
if (ans.startsWith("$GPSGSV")||ans.startsWith("$GPSGGA")) {
lineList.add(ans);
}
}

Dynamically creating objects using a for loop

I'm relatively new to Java and trying to create an application to help with my trading. I have a method to read a csv file that I input, which is table with x number of rows and 3 columns. It reads it as multidimensional String array (String[][]) Eg
Pair----- Buy Price ---Sell Price
AUDUSD 0.9550 --- 0.9386
EURUSD 1.3333 --- 1.3050
GBPUSD 1.5705 --- 1.5550
(please excuse my formatting)
I have a constructor called ForexPair that looks like this:
public class ForexPair extends PriceWarning{
public String pairName;
public double buyPrice;
public double sellPrice;
public ForexPair(String pair, String buy, String sell) {
pairName = pair;
buyPrice = Double.valueOf(buy);
sellPrice = Double.valueOf(sell);
}
My question is this: Can I use a 'for' loop to create an object for each row in my CSV file? I believe I can use an ArrayList for this. However I want the name of each object I create to be the Pair Name in the first column of my csv file. For example:
ForexPair AUDUSD = new ForexPair(pairNames[0], (myArray[0][1]),(myArray[0][2]));
But how do I create the object called AUDUSD using a for loop? So that each object has a different name?
Currently I have this code:
public static void main(String[] args) {
String[][] myArray = getInputArray();
String[] pairNames = new String[myArray.length];
for(int i = 0; i < pairNames.length; i++){
pairNames[i] = myArray[i][0]; //Creates 1D String array with pair names.
ForexPair pairNames[i] = new ForexPair(pairNames[i], (myArray[i][1]),(myArray[i][2]));
}
}
Variable names are not relevant - they aren't even kept track of after your code is compiled. If you want to map names to objects you can instead place ForexPair instances in a Map<String, ForexPair>, i.e.
Map<String, ForexPair> map = new HashMap<String, ForexPair>();
...
// in the for-loop:
map.put(pairNames[i], new ForexPair(pairNames[i], myArray[i][1],myArray[i][2]));
Although this seems slightly redundant, as you already have the name as a field in each ForexPair, so you might want to consider removing this field and keeping track of the name only via the map.
Yes you can. Use a HashMap.
rough example:
HashMap<String, ForexPair> myMap = new HashMap<String, ForexPair>();
myMap.put("AUDUSD", new ForexPair(pairNames[0], (myArray[0][1]),(myArray[0][2])));
ForexPair pair = myMap.get("AUDUSD");
1.
Can I use a 'for' loop to create an object for each row in my CSV file?
Yes, that's possible:
BufferedReader br = new BufferedReader(new FileReader(yourCsvFile));
String line;
while((line = br.readLine()) != null) {
// do something with line.
}
2.
But how do I create the object called AUDUSD using a for loop? So that each object has a different name?
I think your mixing up two different concepts: name of variable and value of your variable called pair
The value of your variable is the important point, while the name of your variable only provides code quality!
final TableLayout tview = (TableLayout) findViewById(R.id.tblGridStructure);
final JSONArray JarraymenuItems = {item1,it3m1mwer,wer,ds};//your list of items
for (int i = 0; i < JarraymenuItems.length(); i++)
{
ableRow tr = new TableRow(this);
tr.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
tview.addView(tr, LayoutParams.FILL_PARENT, 45);
T
final TextView etprice = new TextView(this);
etprice.setText("your text value wat u want to display");
tr.addView(etprice );
int count = tview.getChildCount();
if (count % 2 != 0)
tr.setBackgroundColor(Color.parseColor("#E3E3E3"));
}

Error with reading from file to array

I am trying to read from a file and add each line from the file to my array "Titles" but keep getting the error:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
Any Ideas? I am getting the error because of the line reading:
Titles[lineNum] = m_line;
My code:
String[] Titles={};
int lineNum;
m_fileReader = new BufferedReader(new FileReader("random_nouns.txt"));
m_line = m_fileReader.readLine();
while (m_line != null)
{
Titles[lineNum] = m_line;
m_line = m_fileReader.readLine();
lineNum++;
}
Thank you in advance!
array indexes start with 0. if length of an array is N, then the last index would be N-1. currently your array has a length of zero and you are trying to access an element at index 0(which does exist).
String[] Titles={};//length zero
and in your while loop
Titles[lineNum] = m_line; //trying to access element at 0 index which doesnt exist.
I would suggest you use ArrayList instead of Array in your case. as ArrayList is dynamic (you dont have to give size for it)
List<String> titles = new ArrayList<String>();
while (m_line != null)
{
titles.add(m_line);
}
Array is not growable like ArrayList. Before you add element in string array you need to specify size of String[]
String titles[] = new String[total_lines] ;
or you can simply add each lines in ArrayList then finally convert into an Array like
int totalLineNumbers;
ArrayList<String> list = new ArrayList();
m_fileReader = new BufferedReader(new FileReader("random_nouns.txt")); m_line = m_fileReader.readLine();
while (m_line != null)
{
list.add(m_fileReader.readLine());
}
String titles[] = (String[]) list.toArray();
totalLineNumbers = titles.length ;

Categories