ArrayList Method Returns a null ArrayList, main program cannot access - arraylist

I'm trying to create a basic function that calls on a method that creates the 2D ArrayList that will be used further in the main program to do things like calculate the row and column sums as well as print out the triangle.
However, after it runs the ArrayList returns null. What's going on?
Thanks,
public class Trib
{
private ArrayList<ArrayList<Integer>> triangle;
private int Asize;
public Trib (int size)
{
// convert the argument to type 'int' to be used in the program
Asize = size;
// create an ArrayList of ArrayLists, it will have 'size' number ArrayLists contained within
ArrayList<ArrayList<Integer>> triangle = new ArrayList<ArrayList<Integer>>(size);
// create the inner ArrayLists
for (int i = 0; i < size; i++)
{
// add to index 'i' of our ArrayList a new ArrayList of size (i+1)
triangle.add(new ArrayList<Integer>(i+1));
for (int j = 0; j <= i; j++)
{
if (j==0 || j == i)
{
triangle.get(i).add(1);
}
else
triangle.get(i).add(triangle.get(i-1).get(j-1)+triangle.get(i-1).get(j));
System.out.print(triangle.get(i).get(j) + " ");
}
System.out.println();
}
triangle.clone();
}
public void printTriangle()
{
System.out.print(triangle.get(1).get(1));
/*for (int i = 0; i < Asize; i++)
{
for (int j = 0; j <= i; j++)
{
System.out.print(triangle.get(1).get(1) + " ");
}
System.out.println();
}*/
}
/*public Trib()
{
this(5);
}*/
/*public int Psize()
{
return triangle.size();
}
public ArrayList<Integer> sumRows()
{
ArrayList<Integer> row_sum = new ArrayList<Integer>(Asize);
for (int i = 0; i < Asize; i++)
{
for (int j = 0; j < i; j++)
{
row_sum.add(triangle.get(i).get(j));
}
}
return row_sum;
}
public ArrayList<Integer> sumCols()
{
ArrayList<Integer> col_sum = new ArrayList<Integer>(Asize);
for (int i = 0; i < Asize; i++)
{
for (int j = 0; j < i; j++)
{
col_sum.add(triangle.get(i).get(i));
}
}
return col_sum;
}*/
public static void main(String[] args)
{
if(args.length < 1)
{
System.err.println("Sorry, this program needs an integer argument.");
System.exit(1);
}
Trib pt = new Trib(Integer.parseInt(args[0]));
pt.printTriangle();
//ArrayList<Object> sum_rows = new ArrayList<Object>(pt.Psize());
// sum_rows.add;
System.out.println("\nHere are the sum of rows:");
//for (int i = 0; i < pt.Psize(); i++)
//System.out.println(sum_rows.get(i));
//ArrayList<Integer> sum_cols = new ArrayList<Integer>(pt.Psize());
System.out.println("\nHere are the sum of columns:");
//for (int i = 0; i < pt.Psize(); i++)
//System.out.printf("%-5d", sum_cols.get(i));
}
}

Watch out what's what you are doing: Notice that you have TWO variables named "triangle": The first one is an instance variable and the second is a local variable, which is the only one you have initialized.
My suggestion to avoid this common mistake is to pre-pend "this." to any use of what you intend must be an instance variable. And, if in doubt, if you use a development environment as Eclipse, press CTRL and click on your variable to navigate to the point where it is declared.

Related

How to add JSpinner output into array and check for duplicate

I'm working on a code which has a JSpinner, which gives an output and moves it to int = n, I want to save every JSpinner output and add it into an array to check for duplicates and once found the JPanel should close itself or say you lost.
Scanner s = new Scanner(System.in);
int n = (Integer) spinner.getValue();
if (isPrime(n)) {
Input.setText(n + " is a prime number");
score++;
Highscore.setText("Score: " + score);
int[] array = new int[4];
for(int i=0; i<4;i++)
{
array[i]= (Integer) spinner.getValue();
}
for (int i=0; i < 4;i++)
{
System.out.println(array[i]);
}
Spinner output into array but it fills the whole array with one number example: [3,3,3,3].
private <T> boolean duplicate(T... array)
{
for (int i = 0; i < array.length; i++)
{
for (int j = i + 1; j < array.length; j++)
{
if (array[i] != null && array[i].equals(array[j])) {
return true;
dispose();
}
}
}
return false;
}
Duplicate check
I tried adding the user input from the JSpinner into an array and from there to check for duplicates.
Searched Online but could'nt find anything.
This if my first post so if you need anything more you can tell me.

How to access the values of a dictionary property in a grid using Ocean for Petrel?

I'm tring to access the values of a dictionary property in a grid,such as Fluvial facies or lithologies etc.I have read the coursebook and help docs, but didn't find anything relevant.The coursebook only has examples of creating properties, but not accessing properties.Below is the code I tried:
Grid grid = arguments.Input_Grid;
if (grid == null)
{
PetrelLogger.ErrorStatus("HelloGrid: Arguments cannot be empty.");
return;
}
Index3 currentCell = new Index3();
int maxI = grid.NumCellsIJK.I;
int maxJ = grid.NumCellsIJK.J;
int maxK = grid.NumCellsIJK.K;
for (int i = 0; i < maxI; i++)
{
for (int j = 0; j < maxJ; j++)
{
for (int k = 0; k < maxK; k++)
{
currentCell.I = i; currentCell.J = j; currentCell.K = k;
if (grid.IsCellDefined(currentCell) && grid.HasCellVolume(currentCell))
{
//DictionaryProperty p = ???
//int val = p[currentCell] ???
}
}
}
}
You need to use the "FastDictionaryPropertyIndexer" or "FastPropertyIndexer" for regular properties.
foreach (var dictProp in grid.DictionaryProperties)
{
int numCellsI = dictProp.NumCellsIJK[0];
int numCellsJ = dictProp.NumCellsIJK[1];
int numCellsK = dictProp.NumCellsIJK[2];
float[] values = new float[dictProp.NumCells];
var dpsa = dictProp.SpecializedAccess;
using (var fdpi = dpsa.OpenFastDictionaryPropertyIndexer())
{
int index = 0;
for (int k = 0; k < numCellsK; k++)
{
for (int j = 0; j < numCellsJ; j++)
{
for (int i = 0; i < numCellsI; i++)
{
values[index] = fdpi[i, j, k];
index++;
}
}
}
}
}
You also need to be careful about the indexing since it varies by project. For instance, you may need to reverse the order of traversal in the J direction or you could end up with some strange results.

How I can sort an ArrayList of int arrays?

I have this code. I'm dealing with the N-Queen problem.
The problem is when I wanna show results by screen, the arrays are not ordered. But in this code I can't order them using Comparator. It's very strange because in other Class it works perfectly using Comparator, but here it doesn't work. Hope anyone could help me. Thanks in advance.
import java.util.*;
public class NReinas {
public static void resolverReinas(int n){
String[][] tablero;
tablero = generarTablero(n);
ubicarReina(tablero, 0, n);
}
public static void ubicarReina(String[][] tablero, int etapa, int n){
ArrayList <int[]> resultados = new ArrayList<>();
for(int i = 0; i < tablero.length; i++){
if(isValido(tablero, i, etapa)){
tablero[i][etapa] = "R";
if(etapa < tablero.length - 1){
ubicarReina(tablero, etapa + 1, n); //Recursividad
}else {
resultados.add(devolverSolucion(tablero, n));
}
tablero[i][etapa] = " "; //Backtracking: vaciamos el tablero
}
}
//The ArrayList I want to order by int arrays
for (int[] r : resultados) {
System.out.println(Arrays.toString(r));
}
}
public static boolean isValido(String[][] tablero, int i, int etapa){
for(int x = 0; x < etapa; x++){
if(tablero[i][x].equals("R")){
return false;
}
}
for(int j = 0; j < tablero.length && (i-j) >= 0 && (etapa-j) >=0; j++){
if(tablero[i - j][etapa - j].equals("R")){
return false;
}
}
for(int j = 0; j < tablero.length && (i + j) < tablero.length && etapa - j >= 0; j++){
if(tablero[i + j][etapa - j].equals("R")){
return false;
}
}
return true;
}
public static String[][] generarTablero(int length){
String[][]res = new String[length][length];
for (int i = 0; i < res.length; i++) {
for (int j = 0; j < res.length; j++) {
res[i][j] = " ";
}
}
return res;
}
public static int[] devolverSolucion(String[][] tablero, int n){
int[] solucion = new int[n];
for (int i = 0; i < tablero.length; i++) {
for (int j = 0; j < tablero.length; j++) {
if(tablero[i][j] == "R"){
solucion[i] = j;
}
}
}
return solucion;
}
}
Try Using Integer instead of int and save array values on List instead, so you can use sort them
List<Integer> list = Arrays.asList(solucion);
Collections.sort(list);
If you insist in using and array you can reconverti the list to an array
(Integer[]) list.toArray();

not able to assign value to list declare in model in mvc

My Model Question_Bank_Model:
public List<string> Options { get; set; }
My Controller
for (int i = 0; i < Question_IdLIst.Count; i++)
{
Question_Bank_Model Question = new Question_Bank_Model();
Question.Question = QuestionBal.FetchQuestion_ByQuestionID(Question_IdLIst[i]);
List<string> Options_Value = QuestionBal.FetchOption_ByQuestion(Question_IdLIst[i]);
for (int j = 0; j < Options_Value.Count ; j++)
{
Question.Options[j] = Options_Value.ElementAt(j);
}
q.Add(Question);
}
i am getting value in Options_Value in this list but it is throwing error on
Question.Options[j] = Options_Value.ElementAt(j); line
Error:Object reference not set to instance of object.
can any one help me???
Try this;
Question.Options = new List<string>();
for (int j = 0; j < Options_Value.Count ; j++)
{
Question.Options.Add(Options_Value.ElementAt(j));
}
Thanks!

Retrieving and manipulating data from file

The following code is supposed to retrieve the data related to the players info, sort it out and then rewrite the file now organized. Going to give an example of the files.
Original layout:
3
2 2
John 33 M 5
Anna 20 F 2
Rody 23 M 1
What it has to look like after the code:
3
2 2
Rody 23 M 1
Anna 20 F 2
John 33 M 5
I made the following code:
vector<string> playerScoresFromFile(const string filename) //Gets each one of those lines with the name, ..., and score of the person
{
int dim = filename[7] - '0'; // char to integer
vector<string> vec;
string line;
ifstream fin (filename.c_str());
for (int i = 0; i < dim + 1; i++)
{
getline(fin, line);
}
while(! fin.eof())
{
getline(fin, line);
vec.push_back(line);
}
return vec;
}
vector< vector<int> > readBoardFromFile(const string filename) //gets the board from the file (first 3 numbers)
{
int dim = filename[7] - '0'; // char to integer
string line;
vector< vector<int> >vec(dim, vector<int>(dim));
ifstream fin (filename.c_str());
int i = 0;
int j, k;
while(i < dim)
{
getline(fin, line);
int sizeOfLine = line.length();
if (line[0] == '\0')
{
break;
}
else
{
for (j = 0, k = 0; j < (sizeOfLine / 3); j++, k += 3)
{
string elementOfVectorStr = (line.substr(k,3));
int elementOfVectorInt = stringToInt(elementOfVectorStr);
if (abs(elementOfVectorInt) > 100) // when the element is a " ", the corresponding integer is always
{ // a very large number, positive or negative
elementOfVectorInt = 0;
}
vec[i][j] = elementOfVectorInt;
}
}
i++;
}
return vec;
}
vector<string> sortPlayersByTime (vector<string> &vec) // Creates a substring of the string extracted by "playerScoresFromFile" and analyses the times (Which are the last numbers to the right)
{
vector<int> timesInt(vec.size());
for (size_t i = 0; i < vec.size(); i++)
{
string str = vec[i];
timesInt[i] = stringToInt(str.substr(26));
}
for (size_t i = 0; i < vec.size() - 1; i++)
{
if(timesInt[i] > timesInt[i+1])
{
swap(vec[i], vec[i+1]);
}
}
return vec;
}
bool isOrdered (const vector<string> vec) //Checks if the vector is ordered
{
vector<int> timesInt(vec.size());
for (size_t i = 0; i < vec.size(); i++)
{
string str = vec[i];
timesInt[i] = stringToInt(str.substr(26));
}
for (size_t i = 0; i < vec.size() - 1; i++)
{
if(timesInt[i] > timesInt[i+1])
{
return false;
}
}
return true;
}
void writeBoardToFile(vector< vector<int> >&vec, string filename) //Rewrites the board to the file (Those first 3 numbers of the file)
{
ofstream fout(filename.c_str());
for (size_t i = 0; i < vec.size(); i++)
{
for (size_t j = 0; j < vec.size(); j++)
{
if(vec[i][j] != 0)
{
fout << setw(3) << vec[i][j];
}
else
{
fout << setw(3) << " ";
}
}
fout << endl;
}
fout << endl;
}
void vec_to_file(vector<string> vec, string filename) //Rewrites the vector to the file
{
ofstream fout(filename, ios::app);
for (int i = 0; i < vec.size(); i++)
{
fout << vec[i] <<endl;
}
}
void displayFile (string filename) //Displays the final board to check if it worked
{
vector<string> vec;
string line;
ifstream myfile (filename);
while ( ! myfile.eof() )
{
getline (myfile, line);
vec.push_back(line);
}
for (size_t i = 0; i < vec.size(); i++)
{
cout << vec[i] <<endl;
}
}
int main()
{
vector< vector<int> > vec = readBoardFromFile("puzzle_2x2_001.txt");
vector<string> vecxz = playerScoresFromFile("puzzle_2x2_001.txt");
writeBoardToFile(vec, "puzzle_2x2_001.txt"); //Writes the board to the file
while (! isOrdered(vecxz)) //This loop should run while they haven't been sorted out, but the program crashes here and I have no idea why.
{
sortPlayersByTime(vecxz);
}
//vec_to_file(vecxy, "puzzle_2x2_001.txt"); //Should write the vector to the file upon sorting them out successfully.
cin.get();
}
My problem is the program crashes everytime it gets to the while(! isOrdered(vecxz)) loop but I have no idea why. Can anyone give me a hand? I'd be thankful :)