Ega Suhandianto
Ega Suhandianto

Reputation: 27

how to store data in arrays, use functions for

I want to save data into an array using the for function. the following script is used:

int[] U;
int k = 0;

String ukecil = i.getStringExtra("ukecil");
String ubesar = i.getStringExtra("ubesar");

int ukk = Integer.parseInt(ukecil);
int ukb = Integer.parseInt(ubesar);

for (int j=ukk; j<=ukb; j++){
  U[k]= j;
  k++;
}

tx_uk1.setText(U[0]);
tx_uk2.setText(U[1]);
tx_uk3.setText(U[2]);

then I want to display data in text view. but there is an error which is:

java.lang.NullPointerException: Attempt to write to null array

this section error:

U[k]= j;

Upvotes: 1

Views: 73

Answers (2)

Vishnu
Vishnu

Reputation: 785

Here's the full code

ArrayList<Integer> U = new ArrayList<>();
int k = 0;

String ukecil = i.getStringExtra("ukecil");
String ubesar = i.getStringExtra("ubesar");

int ukk = Integer.parseInt(ukecil);
int ukb = Integer.parseInt(ubesar);

for (int j=ukk; j<=ukb; j++){
     U.add(k++,j);//Updated
}

tx_uk1.setText(U.get(0)+"");
tx_uk2.setText(U.get(1)+"");
tx_uk3.setText(U.get(2)+"");

Hope this helps.......

Upvotes: 1

fatalcoder524
fatalcoder524

Reputation: 1480

You need to specify the size of the array.

int[] U=new int[size];

If you want dynamic size, use ArrayList.

ArrayList<Integer> U = new ArrayList<Integer>();
U.add(k++,j); //index,element

Upvotes: 2

Related Questions