Converting byte array to integer - last value always converts to zero - java

When converting my byte array to an integer array for calculations, the integer array should be the same values as the byte array. However, in my integer array, the last array value always outputs as zero.
for (int i = 0; i < arrCalc.length; intArray[i] = arrCalc[i++])
In this case, the arrCalc values are [97,98,99], and after the above code runs, intArray is showing [97,98,0] instead of [97,98,99]. Can anyone explain why this is and/or how to fix it?
*Note - I generally don't program in Java...if that matters at all...

The problem is your postfix. It is processed before you think it is.
Try breaking the code (besides, it is more Java-style compliant):
for (int i = 0; i < arrCalc.length; i++) {
intArray[i] = arrCalc[i];
}
Oracle Site about Operator Precedence
The operators in the following table are listed according to
precedence order. The closer to the top of the table an operator
appears, the higher its precedence.

Related

Calculate absolute minimum difference between any two numbers of a huge integer array

I have a very long array in a Java program (300 000+ unsorted integers) and need to calculate the minimum absolute difference between any two numbers inside the array, and display the absolute difference and the corresponding pair of numbers as an output. The whole calculation should happen very quickly.
I have the following code, which would usually work:
private static void calcMinAbsDiff(int[] inputArray)
{
Arrays.sort(inputArray);
int minimum = Math.abs(inputArray[1] - inputArray[0]);
int firstElement = inputArray[0];
int secondElement = inputArray[1];
for (int i = 2; i < inputArray.length; i++)
{
if(Math.abs(inputArray[i] - inputArray[i-1]) < minimum)
{
minimum = Math.abs(inputArray[i] - inputArray[i-1]);
firstElement = inputArray[i-1];
secondElement = inputArray[i];
}
}
System.out.println("Minimum Absolute Difference : "+minimum);
System.out.println("Pair of Elements : ("+firstElement+", "+secondElement+")");
}
However, the output I receive is all 0s. I believe this is because the array is way too long.
If you have two or more zeros and no negative integers in your dataset, then your output is expected. After sorting, then inputArray[0] and inputArray[1] would both be 0, and the difference would be 0. No other pair of adjacent elements would have an absolute difference less than 0, so minimum, firstElement, and second Element would all be 0 at the end of the algorithm.
If you really have no zeros in your dataset, or if you do have negative integers, then you may have an initialization problem. Check this thread:
Why is my simple Array only printing zeros in java?
If that's not it, then only other thing I can think of is that you have a problem in the previous scope causing the data to get zeroed out.
I would try printing samples of your dataset at various points to see exactly where/when it's getting zeroed.
If you still have trouble, then post more info on the dataset and the scope which calls this function to help us see what's going on. Let us know how you make out!

why do my averages not print out the way they're supposed to? [duplicate]

for (int i = 0; i < reports.length; i++) {
Products[] products = reports[i].getDecisions;
for (int j = 0; j < products.length; j++) {
}
}
Here I want to index the inner for loop starting from 1 , but it is not working as expected, I also changed the j
Java arrays are always 0-based. You can't change that behavior. You can fill or use it from another index, but you can't change the base index.
It's defined in JLS §10.4, if you are interested in it.
A component of an array is accessed by an array access expression (§15.13) that consists of an expression whose value is an array reference followed by an indexing expression enclosed by [ and ], as in A[i].
All arrays are 0-origin. An array with length n can be indexed by the integers 0 to n-1.
You can't do that as array index in Java starts from 0.
But you can access array with index 1 with little modifications.
Example:
Consider an integer array "a" with length n
for(int i=0;i<n;i++) {
System.out.println(a[i]);
}
This can be modified as:
int a[] = new int[n+1];
for(int i=1;i<n+1;i++) {
System.out.println(a[i]);
}
Just like in most languages arrays are indexed from 0. You better get used to it, there is no workaround.
Base Index of Java arrays is always 0. It cannot be changed to 1.
You can use pointers, to jump to a certain point of the array and start the array from there.
For example:
char str[20];
str={'H', 'E' ,'L' ,'L', 'O','W' ,'O ','R','L',' D'};
char *ptr;
*ptr=str[0];
//right now its pointing to the starting.
ptr=ptr+3;
//Now pointing at 3rd unit.
This doesn't work in every compiler.This is the closest thing that can be done for your question.
its all simple that in C , C++ , Java or etc.. the array index start from "0" only. and we can't change it. but sometimes in some Practice problems we are asked to use 1-indexed-based array, which we actually can't do that, so to tackle that, just leave 0th-index aside, and start using the array from 1th-index onwards, and while solving the situation always keep in mind that we have to never include or use that 0th-index in our operations.

How I can index the array starting from 1 instead of zero?

for (int i = 0; i < reports.length; i++) {
Products[] products = reports[i].getDecisions;
for (int j = 0; j < products.length; j++) {
}
}
Here I want to index the inner for loop starting from 1 , but it is not working as expected, I also changed the j
Java arrays are always 0-based. You can't change that behavior. You can fill or use it from another index, but you can't change the base index.
It's defined in JLS §10.4, if you are interested in it.
A component of an array is accessed by an array access expression (§15.13) that consists of an expression whose value is an array reference followed by an indexing expression enclosed by [ and ], as in A[i].
All arrays are 0-origin. An array with length n can be indexed by the integers 0 to n-1.
You can't do that as array index in Java starts from 0.
But you can access array with index 1 with little modifications.
Example:
Consider an integer array "a" with length n
for(int i=0;i<n;i++) {
System.out.println(a[i]);
}
This can be modified as:
int a[] = new int[n+1];
for(int i=1;i<n+1;i++) {
System.out.println(a[i]);
}
Just like in most languages arrays are indexed from 0. You better get used to it, there is no workaround.
Base Index of Java arrays is always 0. It cannot be changed to 1.
You can use pointers, to jump to a certain point of the array and start the array from there.
For example:
char str[20];
str={'H', 'E' ,'L' ,'L', 'O','W' ,'O ','R','L',' D'};
char *ptr;
*ptr=str[0];
//right now its pointing to the starting.
ptr=ptr+3;
//Now pointing at 3rd unit.
This doesn't work in every compiler.This is the closest thing that can be done for your question.
its all simple that in C , C++ , Java or etc.. the array index start from "0" only. and we can't change it. but sometimes in some Practice problems we are asked to use 1-indexed-based array, which we actually can't do that, so to tackle that, just leave 0th-index aside, and start using the array from 1th-index onwards, and while solving the situation always keep in mind that we have to never include or use that 0th-index in our operations.

Simple Number to Array with Individual Digits

I am exceptionally new to programming, but I am working on improving my skills as a programmer. Currently, I am working on a problem I gave myself where I am trying to take a variable number and make each of its digits a separate number in an array. I don't care about the order of the digits, so if they are reversed, then it doesn't matter to me. I know people have asked this question numerous times, but they always seem to use a lot of things that I don't understand. Since my school doesn't offer any Java courses, I only know what I have learned on my own, so if you could explain any terms you use in the code that aren't extremely trivial, that would be wonderful. Right now, I have written:
int number = 1234567890;
while (number > 0) {
System.out.println(number%10);
number = number/10;
This works fine for printing the digits individually, but I can't figure out how to add them to the array. I greatly appreciate any help you can give, and please keep in mind that I much prefer simplicity over small size. Thank you in advance!
P.S. Some responses I've seen for similar questions include what I think are arrays of strings. In order for the part of the program that I have working to still work, I think that I need to use an array of integers. If you're curious, the rest of the code is used to determine if the numbers in the array are all different, in order to achieve the final result of determining if a number's digits are all distinct. It looks like this:
int repeats=0;
int[] digitArray;
digitArray = new int[10];
for (int i = 0; i < digitArray.length; i++)
for (int j = 0; j < digitArray.length; j++)
if ((i != j) && (digitArray[i]==digitArray[j])) unique = unique+1;
System.out.println(unique==0);
Method number.toString().length() will return the number of digits. That is the same as the length of your needed array. Then you use your code as before, yet instead of printing you add the digit to the array.
int number = 1234567890;
int len = Integer.toString(number).length();
int[] iarray = new int[len];
for (int index = 0; index < len; index++) {
iarray[index] = number % 10;
number /= 10;
}
I would rather suggest you to use an ArrayList, since to use an array, you would have to allocate the size in advance, for which you need to know the number of digits in your number, which you don't know.
So, either work with an array, and do the iteration over the number twice - once for finding size, and next for doing actual work. Else, move ahead with an ArrayList.
Adding an element to an ArrayList is quite simple. You just need to call - List#add(E) method with appropriate parameter.
So, here's an extension of your solution: -
// Declare a List<Integer>, since it will store integers only.
List<Integer> digits = new ArrayList<Integer>():
int number = 1234567890;
while (number > 0) {
int digit = number % 10; // Store digit in a variable
number = number/10;
// Add digit to the list
digits.add(digit);
}
Alternatively, if you want to have only unique digits in your List, then you should use a HashSet, which automatically removes the duplicates.
With Java 8:
Integer.toString(n).chars().map(a->a-'0').toArray()
char [] arr = scan.next().toCharArray();
This code will read a number from scan.next() and then it is going to give it as an input to char array which will have the number at its indices as single digit by digit.
Hope this will help.

Getting ArrayIndexOutOfBoundsException after a Certain INPUT value

for the Given below code after int Input Value of 46348 i am getting ArrayIndexOutOfBoundsException. I am given Condition in for loop that keeps the array limits. But somehow i am getting this exception and i unable to figure it out. And my requirement is find all primenumbers below given number.
Scanner sc = new Scanner(System.in);
int n= sc.nextInt();
int[] arr= new int[n+1];
for(int i=2;i<=n;i++)
{
if(arr[i]==0)
{
for(j=i;j*i<=n;j++)
arr[j*i]=1; // Here i am getting Exception
}
}
Input:
46349
Output:
java.lang.ArrayIndexOutOfBoundsException: -2146737495
502802
Thanks.,
You have encountered an arithmetic overflow.
In Java, int data type is a 32-bit signed integer, which means it can have values between -2147483648 and 2147483647.
On this line:
for(j=i;j*i<=n;j++)
If i is 46349 then j becomes 46349, too. If you multiply 46349 by 46349, you get 2148229801, which is greater than 2147483647, so the integer overflows and becomes -2146737495. Naturally, it is less than 46349, so the check in the for-loop passes. But you cannot index an array with a negative value in Java, that's why you get the ArrayIndexOutOfBoundsException.
Range check your input value for n < 46340, or if it really needs to work with n = 46349 input, switch to long data type, which will work up to n = 3037000499.
46349 * 46349 is too big to use as the index of a Java Array. The index is just a 32-bit signed integer, so has a maximum value of 2,147,483,648.
It passes the < n check because it overflows and comes back negative, so it is in fact less than n, but a negative number is not a legal array index.

Categories