How do I debug arrays? [closed] - java

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 10 months ago.
Improve this question
I have this assignment that I am having trouble on. I'm supposed to fix syntax error in the code to produce the desired number. I fixed the amount of arrays from 4 to 3 and added "[]" to the end of array in the for loop. I don't know what else there is to fix. Can anyone help?
//
// Fix the compiler errors. The program should display the value 6.
//
package debug5;
public class debug5 {
public static void rain(String[] args) {}
int val = 0; // initialize val to 0.
int array[] = new int[3]; // create an array of 3 integers.
array[0] = 1;
array[1] = 2;
array[2] = 3;
array[3] = 4;
// add up the values in the array.
for (int zx = 0;zx < array.length;zx++)
}
val += array;
{
system.out.println(val);
}
}
My version :
//
// Fix the compiler errors. The program should display the value 6.
//
package debug5;
public class debug5 {
public static void rain(String[] args) {}
int val = 0; // initialize val to 0.
int array[] = new int[3]; // create an array of 3 integers.
array[0] = 1;
array[1] = 2;
array[2] = 3;
// add up the values in the array.
for (int zx = 0;zx < array.length;zx++)
}
val += array[];
{
system.out.println(val);
}
}

In addition to Rafael's answer, be careful with braces and where you'd like to system out.
public static void rain(String[] args) {
int val = 0; // initialize val to 0.
int[] array = new int[3]; // create an array of 3 integers.
array[0] = 1;
array[1] = 2;
array[2] = 3;
//add up the values in the array.
for(int zx = 0;zx < array.length ;zx++){
val += array[zx];
}
System.out.println(val);
}
Above code will increment val with each value inside the array and sum inside val variable. Print is done afterwards.
There were some issues with your array initialization and use of arrays and indexes. I suggest you read a bit more on this because this is important on programming
Finally, a better name for the index variable would be i or index instead of zx.

Try this:
val += array[zx];
You have to use the index of the array.

Related

Getting Error: java.lang.NullPointerException when work with Array in Java [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 2 years ago.
import java.util.Scanner;
public class Java3{
int sumAll = 0;
int sumFive = 0;
int sumLast = 0;
int arr[];
int n;
void arraySum(int[] arr) {
for (int i = 0; i < arr.length; ++i) {
sumAll += arr[i];
if (i == 4)
sumFive += sumAll;
if (i >= (arr.length - 5))
sumLast += arr[i];
}
System.out.println("sum all = " + sumAll
+ " sum first five " + sumFive
+ " sum last five " + sumLast);
}
public static void main(String [] args) {
Java3 obj1 = new Java3();
Scanner scan1 = new Scanner(System.in);
System.out.println("enter the number of elements");
obj1.n = scan1.nextInt();
System.out.println("enter the elements");
for (int i = 0; i < obj1.n; ++i)
obj1.arr[i] = scan1.nextInt();
obj1.arraySum(obj1.arr);
}
}
The error I get
java.lang.NullPointerException
Errors on Null pointer exception has been asked and answered several times before, but I do not understand those explanations. Can anyone please explain it in a very easy manner. This is my code, and it is showing me the error at runtime.
This code is supposed accepts the size of an integer array followed by the integer array. Then calls a function which calculates:
sum of all digits
sum of first 5 digits
sum of last 5 digits
and prints each value in the console..
Seems like you are a beginner in coding, nullPointerException occurs whenever you are trying to access the value of an object that is not defined.
In your case you did not define your array. You should have defined your array as given below before trying to add values into the array this will remove the exception.
obj1.arr = new int[obj1.n];
Doing this will define your array in your object and with obj1.n it will initialize its size. Hope you can proceed from here. Please refer the usage of new and constructors in java.
The problem was you took the length of array as input , but you did not initialize the array . Please add this one line in the code:
obj1.n = scan1.nextInt();
obj1.arr = new int[obj1.n];
You should define your arr size. until you define the arr size it is null, and there is no memory will be allocated. You can avoid this by using ArrayList instead of array or define your arr with sum big number of size and asker user to enter the number of values less than that size.
int arr[] = new int[100];
define the array size once you know the value
obj1.arr = new int[obj1.n+1];

readNumberAsArray assignment [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
Write a readNumberAsArray method that takes an integer as a parameter and creates a new int array with that number as the length. Subsequently, a corresponding number of int values ​​should be read in with the aid of the IOTools and the array filled with them returned, whereby only single-digit numbers (0-9) should be taken into account as input. If the parameter is negative, the method should return null. For negative or two-digit value entries, the entered value should be replaced by 0. Use a for loop to read in the values. A text output when using the IOTools is not necessary.
My program is not working.
import Prog1Tools.IOTools;
package com.company;
public class Main {
public static void readNumberAsArray(int a) {
int [] a = new int[];
int a = IO.Tools.readInteger () ;
for int (a = 0 ; a<10 ; --a) {
System.out.println('0');
for (int a=0; a>10; a++) {
System.out.println(a);
for (int a=10; a=>10; a++) {
System.out.println('0');
}
}
}
// write your code here
}
}
I think you have to just implement what you're asked. Step by step. There's no special logic.
public int[] readNumberAsArray(int n) {
// negative or two-digit values should be replaced with 0
if (n <= 0 || n > 9)
return new int[0];
// creates a new int array with that number as the length
int[] arr = new int[n];
// corresponding number of int value should be read in with the aid of the IOTools
for (int i = 0; i < arr.length; i++)
arr[i] = IO.Tools.readInteger();
return arr;
}

Compare name of String and name of Array int[] [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
I have one matrix which has two rows and one column. Each row has specific name such as row0 and row1. I added some numbers in each row and column of this matrix. For example I have String index which can get one of the name of rows (row0 or row1). How can I check if index == "row0" then print row0[1] and if index == "row1" then print row1[1]??
int[][] s = new int[2][3];
s[0][0] = 5;
s[0][1] = 10;
s[0][2] = 15;
s[0][1] = 25;
s[1][1] = 30;
s[2][1] = 45;
int[] row0 = new int[]{s[0][0], s[0][1], s[0][2]};
int[] row1 = new int[]{s[0][1], s[1][1], s[2][1]};
String index = "row0";
// if index= row0
System.out.println(row0[1]);
// if index=row1
System.out.println(row1[1]);
In your example there is probably something wrong:
int[][] s = new int[2][3]; // two rows, three cols
s[0][0] = 5;
s[0][1] = 10;
s[0][2] = 15;
s[0][1] = 25;
s[1][1] = 30;
s[2][1] = 45; // <---- 2 is out of bounds
int[] row0 = new int[]{s[0][0], s[0][1], s[0][2]};
int[] row1 = new int[]{s[0][1], s[1][1], s[2][1]};
Anyway, you could use a Map for your matrix and then address the rows with a String:
// ...code for s here..
Map<String, Integer[]> matrix = new HashMap<String, Integer[]>();
matrix.put("row0", new Integer[] {s[0][0], s[0][1], s[0][2]});
matrix.put("row1", new Integer[] {s[0][1], s[1][1], s[2][1]});
String index = "row0";
// if index= row0
System.out.println(matrix.get(index)[1]); // row0[1]
// if index=row1
index = "row1";
System.out.println(matrix.get(index)[1]); // row0[1]
You can not check the equality of String objects with the == operator.
You have to use .equals() instead. This question has been asked many times in StackOverflow and this answer, explains it concisely.
What you want to do, is something like this:
final String ARRAY_NAME1 = "row0";
final String ARRAY_NAME2 = "row1";
String index = "row0";
if(index.equals(ARRAY_NAME1))
System.out.print(row0[1]);
else if((index.equals(ARRAY_NAME2))
System.out.print(row1[1]);
We got that out of the way.
Now, you say that you don't want to hardcode this and I absolutely understand.
So, if I were in your position, I would create a new class for this. It's really simple and easy to do, even for a total beginner.
//class can be named anything. (As long as it is meaningful)
public class IntegerArrayIdentity{
/*This class will have two variables.
A name, for comparison operations and
the integer array that it will represent.*/
public String name;
public int[] array;
/*Simple constructor. Takes the name and array as its parameters.
You can change it to only take a name as a parameter, in case
that you want to initialise the array later. Add new methods as you like*/
public IntegerArrayIdentity(String name, int[] array){
this.name = name;
this.array = array;
}
}
Then in your code, you can do:
int[] row0 = {8, 3, 5, 143, 27, 0};
IntegerArrayIdentity row0id = new IntegerArrayIdentity("row0", row0);
if(index.equals(row0id.name))
System.out.println(row0id.array[1]);
output -> '3'
All the above is just an example. You can implement it however you like.
Hope it helped.

Produce repmat() method using java

we have the repmat(arr,2,1,2) method in matlab produce a format which is :
arr = [6,3,9,0];
L(:,:,1) =
6 3 9 0
6 3 9 0
L(:,:,2) =
6 3 9 0
6 3 9 0
the java code that i tried to produce same format is
class test24{
public static void main ( String [] args ) {
int[] arr = {6,3,9,0};
test24 test = new test24();
System.out.println(Arrays.deepToString(test.repmat(arr,2,1,2)));
}
public static int[][][] repmat (int[] array, int rows, int columns, int depth)
{
int arrayColumns = array.length;
int resultColumns = arrayColumns * columns;
int[][][] result = new int[rows][resultColumns][depth];
int z = 0;
for (int d = 0; d < depth; d++)
{
for (int r = 0; r < rows; r++)
{
for (int c = 0; c < resultColumns; c++)
{
result[r][c][d] = array[z++];
if (z >= arrayColumns)
{
z = 0;
}
}
}
}
return result;
}
}
the the result from the java code is :
[[6,6],[3,3],[9,9],[0,0]],[[[6,6],[3,3],[9,9],[0,0]]???
please any suggestion
I believe that the depth argument causes that each value within the array has two values (int[][][] result = new int[rows][resultColumns][depth]; would become (given the inputs rows=2, columns=1 and depth=2 and an initial array of 4) new int[2][1][2]).
Not entirely sure what the repmat method exactly should do put it might be that changing the creation of the array into int[][][] result = new int[depth][rows][resultColumns]; fixes the issue.
I imagine that this is because MATLAB used column-major indexing whereas Java uses Iliffe vectors. So MATLAB stores multidimensional vectors using a single contiguous block of memory where Java stores an array of pointers and each pointer points to another array.
It's difficult to tell exactly what the Java data-structure your code resulted in was. Do you think maybe you could rather post a screen shot from a debugger? What you have now does not look correct, the brackets don't even match.
At a guess though, I would suggest that you maybe change this line
result[r][c][d] = array[z++];
To something more like
result[d][r][c] = array[z++];
Or possibly to even alter the inner loop to something like
for (int c = 0; c < columns; c++) {
result[d][r][c] = array;
}

Remove all occurrences of an integer from an int array [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
How can I remove all occurrences of an integer, say, 17 in this example from a given array in java?
I tried setting entries to (Integer) null though it doesn't work.
Input array: [0,6,0,17,1,9,17,8,4]
Output array: [0,6,0,1,9,8,4]
for(int i =0;i<ansa.length;i++){
if(ansa[i]==17)
{
ansa[i]=(Integer)null;
}
}
This results in
Exception in thread "main" java.lang.NullPointerException
int[] array = { 0,6,0,17,1,9,17,8,4 };
int[] filtered = Arrays.stream(array).filter(i -> i != 17).toArray();
System.out.println(Arrays.toString(filtered));
:-)
Try this one.
Integer[] array ={0,6,0,17,1,9,17,8,4};
List<Integer> list = new ArrayList<Integer>( Arrays.asList(array ));
list.removeAll(Arrays.asList(17 ));
array =list.toArray(new Integer[0]);
System.out.println(Arrays.toString(array));
I tried setting entries to (Integer) null though it doesn't work.
Of course it doesn't, because the size of the array isn't changed. In order to do this, some of the defined java collections (in particular, the ArrayList and Iterator classes) can provide you of a better approach.
In pseudocode:
Turn array into a List
Iterate over its elements
If the element is the given number
Remove it
Return the List as an Array
You can fill in the blanks, just remember that you can't actually remove an element from an array, because its size is static.
Note: I'm going for the educational approach.
This seems to work - although I suspect people will post better/more efficient solutions.
public void test() {
int[] before = new int[] {0,6,0,17,1,9,17,8,4};
int[] after = remove(before, 17);
System.out.println("Before: "+Arrays.toString(before));
System.out.println("Aftre: "+Arrays.toString(after));
}
private int[] remove(int[] before, int remove) {
// Work out how long it must be.
int keep = 0;
for ( int i = 0; i < before.length; i++ ) {
if(before[i] != remove) {
keep += 1;
}
}
// Make the new one
int[] after = new int[keep];
// Fill it in.
for ( int i = 0, j = 0; i < before.length; i++ ) {
if(before[i] != remove) {
after[j++] = before[i];
}
}
return after;
}
Thats one possible solution:
int[] array1 = new int[]{0,6,0,17,1,9,17,8,4};
ArrayList<Integer> result = new ArrayList<Integer>();
boolean flag = true;
for(int i = 0; i < array1.length; i++) {
for(int j = 0; j < array1.length; j++) {
if(array1[i]==array1[j]&&i!=j) {
flag = false;
}
}
if(flag) {
result.add(array1[i]);
}
else{
flag = true;
}
}
System.out.println(result);
I think, if you don't want to use an ArrayList, you will have to count how many 17 are in the array and create a new one with ansa.length-count fields
You cannot remove items from an array you are currently using a for loop to cycle through. At the moment you are getting to the end of your array and looking for the next value even though you deleted it. The array length indicator (ansa.length) does not auto update as you are thinking.
You should use List and an iterator to cycle through the list.
You can use then use the .remove function
You are almost done!!
Integer[] ansa = new Integer[] { 0, 6, 0, 17, 1, 9, 17, 8, 4 };
for (int i = 0; i < ansa.length; i++) {
if (ansa[i] == 17) {
ansa[i] = (Integer) null;
}
}
for (Integer integer : ansa) {
System.out.print(integer+","); //0,6,0,null,1,9,null,8,4,
}
You are facing issue, Because you declared primitive I guess like,
int[] ansa = new int[] // Primitive

Categories

Resources