how to store data in arrays, use functions for - java

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;

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

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.......

Related

Print variables, excluding ones that are zero

Let's say I have five int variables that are prompted for user input. User keys in the five value and two of those values are 0. I would like to ONLY print out values that are greater than zero.
int v1 = 1;
int v2 = 30;
int v3 = 0;
int v4 = 37;
int v5 = 0;
I would like to write a dynamic print statement that would exclude the int variables with Zero value.
Currently, my print statement displays all values:
System.out.printf("%s %d%n%s %d%n%s %d%n%s %d%n%s %d%n","V1;","v1","V2:","v2","V3:","v3","V4:","v4","V5:","v5");
I tried writing if-else statements but that became very cumbersome.
Create a new method printNonZeroVars(Integer... ints).
public static void main(String[] args) {
int v1 = 1;
int v2 = 30;
int v3 = 0;
int v4 = 37;
int v5 = 0;
printNonZeroVars(v1, v2, v3, v4, v5)
}
public void printNonZeroVars(int... ints) {
for (int i = 0; i < ints.length; i++) {
if (ints[i] > 0) {
System.out.printf("V%d%d%n", i, ints[i]);
}
}
}
I would use an array.
Iterate over the array and with an if you can check whether your current value is 0.
So a simple way of achieving this would be to use some sort of Array/List.
ArrayList<Integer> list = new ArrayList<Integer>()
// Or as pointed out by David a better way would be to declare the list as
List<Integer> list = new ArrayList<>();
list.add(5);
list.add(1);
list.add(0);
....
Once you have the list you can use a loop to loop through the list and do relevant checks - something like this
String str = "";
for(int i=0; i<list.size(); i++) {
if(list.get(i) == 0) {
continue;
}
str += "v"+i + ":" + Integer.toString(list.get(i));
}
System.out.println(str);
Its pseudo but should give you a good head start :)

How to use create 2 Array with User input with Std.readAllInts()

This is how it should work, i Put in put for the 1 st array like: 2 3 1 2 3 4 5 6 then 2 and 3 are row and colum and the rest are the values. Problem is the 1st array work, but when i reach EOF ( ctrl+z) then there is out of bound exception. Which mean i cant input value for the 2nd Array like the 1st one. I know there is anotherway where that i can declare array size first then value. But how could i fix this f i still want to usr StdIn.readAllInts() ?
public class MatrixMult {
public static void main(String[] args){
System.out.println("First Matrix Config");
int[] einGabeMatrix1= StdIn.readAllInts();
int zeileM1 = einGabeMatrix1[0];
int spalteM1 = einGabeMatrix1[1];
int[][] ersteMatrix= new int [zeileM1][spalteM1];
int k=2;
int sum;
for(int i=0;i<zeileM1-1;i++){
for(int j=0;j<spalteM1-1;j++){
ersteMatrix[i][j]=einGabeMatrix1[k];
k++;
}
}
System.out.println("Second Matrix Config");
int[] einGabeMatrix2 = StdIn.readAllInts();
int zeileM2 = einGabeMatrix2[0];
int spalteM2 = einGabeMatrix2[1];
int h=2;
int[][] zweiteMatrix= new int [zeileM2][spalteM2];
for(int m=0;m<zeileM2-1;m++){
for(int n=0;n<spalteM2-1;n++){
zweiteMatrix[m][n]=einGabeMatrix2[h];
h++;
}
}
int[][] ergebnisMatrix= new int [zeileM1][spalteM2];
for (int t = 0; t < zeileM1; t++) {
for (int c = 0; c < spalteM2; c++) {
sum = 0;
for (int d = 0; d < spalteM1; d++) {
sum = sum + ersteMatrix[t][d] * zweiteMatrix[d][c];
}
ergebnisMatrix[t][c] = sum;
}
}
for(int i=0;i<zeileM1;i++){
for(int j=0;j<spalteM1;j++){
System.out.println(ergebnisMatrix[i][j]);
}
}
}
}
// This is StdIn.readAllInts(), standard method by java.
public static int[] readAllInts() {
String[] fields = readAllStrings();
int[] vals = new int[fields.length];
for (int i = 0; i < fields.length; i++)
vals[i] = Integer.parseInt(fields[i]);
return vals;
}
It looks like the issue is coming from the fact that StdIn.readAllInts() reads until the EOF. There will be no values left to read by the time your code gets to the second call.
I would suggest instead using the StdIn.readInt() call to read each integer one at a time and then you can use it within your loop to read the exact number of values your need.
Here is an example of how you could get the first 2 integers to find your matrix size:
int zeileM1 = StdIn.readInt();
int spalteM1 = StdIn.readInt();
You will also need to apply this method in your for loops to read the data into the matrix.

Java - Array <init> error

So, I have this class, that contains another class array, and in the constructor I want to make "n" and "nCod" equal 0.
public class ITable
{
TableRow arr[];
class TableRow
{
long n;
int nCod;
ICode cod;
}
ITable()
{
arr = new TableRow[256];
for(int i=0;i<256;i++)
{
arr[i].n = 0;
arr[i].nCod = 0;
}
}
}
When I run it, Eclipse console tells me:
java.lang.NullPointerException
at jhuffman.def.ITable.<init>(ITable.java:21)
That line is:
arr[i].n = 0;
When you create an array instance with new TableRow[256], each of its elements are initialized to null.
Therefore, each element should be initialized before being accessed :
arr = new TableRow[256];
for(int i=0;i<256;i++)
{
arr[i] = new TableRow (); // add this
arr[i].n = 0;
arr[i].nCod = 0;
}
When you create an object array with no initial values, all the positions in the array will point to null. So, for example, arr = new TableRow[3] would initialize the array as [null, null, null].
Since you did not store any TableRow objects into arr, when you access arr[i], it returns null instead of a concrete object. If you try to access a field in null it will result in a NullPointerException as you have observed.
What you need to do is create the TableRow instances and place them into the array before you try to access them. Something like this:
arr = new TableRow[256];
for (int i = 0; i < arr.length; i++) {
arr[i] = new TableRow();
arr[i].n = 0;
arr[i].nCode = 0;
}

ArrayList giving problems in java. positive integers solution to x+y+z+w = 13

So i am creating a method that basically gives all possible positive integer solutions to the problem x+y+z+w = 13. Really I have designed a program that can get all possible positive integer solutions to any number using any number of variables. I have managed to obtain the solution using this method:
public class Choose {
public static ArrayList<int[]> values;
public static void main(String[] args) {
// TODO Auto-generated method stub
int[] loops = new int[3];
int q = 0;
values = new ArrayList<int[]>();
int[] array = new int[4];
System.out.println(choose(12,3));
NestedLoops(3,10,0,loops,13,array, 0);
for(int i = 0; i < values.size(); i++){
printArray(values.get(i));
}
}
public static void NestedLoops(int n, int k, int j,
int[] loops, int q, int[] array, int g){
if(j==n){
for(int i = 0; i< n; i++){
q-=loops[i];
}
if(q>0){
for(int i = 0; i < n; i++){
array[i] = loops[i];
}
array[n] = q;
values.add(array);
}
return;
}
for(int count = 1; count <= k; count++){
loops[j] = count;
NestedLoops(n,k,j+1,loops, 13, array, g);
}
}
}
My problem is that when i go to print the ArrayList, all i get is the last value repeated again and again. When i try to just print out the values instead of storing them in the ArrayList it works totally fine. This makes me think that the problem is with the values.add(array); line but i don't know how to fix it or what i am doing wrong. Thanks for any help offered.
Try using:
values.add(array.clone());
Every add of the same array just points to that array object. As you keep changing the same object, the final state is what is being shown for all stored elements. The print works as it just dumps the state of the array at that particular instant.

Shuffle the Integer of the Object<Integer,String> in a List/ArrayList

List<Data> list = new ArrayList<Data>();
public class Data{
public int n;
public String p;
public Data(int N, String P) {
n = N;
p = P;
}
}
How can i shuffle the Integer of the Object: Data. So the String stays at the same position, and the Integer get's shuffled.
Loop through list and store the int of each Data object in a separate list. Shuffle this list using Collections.shuffle(...). Loop through this new shuffled list and set the n field of each corresponding member of list to the new random int found in the shuffled list.
Probably have to do it yourself:
for (int i = list.size(); i > 0; i--) {
int j = (int)(Math.random() * (i + 1));
int temp = list.get(i).n;
list.get(i).n = list.get(j).n;
list.get(j).n = temp;
}
The best you can do from java libraries is to first split it into two lists, one of ints and one of strings, then shuffle only the ints (using Collections.shuffle), then combine the two lists back into one list of Datas
You could use something like this:
List<Integer> ns = new ArrayList<Integer>(list.size());
for (Data data : list) {
ns.add(data.n);
}
Collections.shuffle(ns);
for (int i = 0; i < list.size(); i++) {
Data data = list.get(i);
int newN = ns.get(i);
data.n = newN;
}
Note that it's best practice to use accessors getN() and setN(int) and make Data.n private.

Categories