How to find integer array size in java - java

below is my code which is throwing error:
Cannot invoke size() on the array type int[]
Code:
public class Example{
int[] array={1,99,10000,84849,111,212,314,21,442,455,244,554,22,22,211};
public void Printrange(){
for (int i=0;i<array.size();i++){
if(array[i]>100 && array[i]<500)
{
System.out.println("numbers with in range ":+array[i]);
}
}
Even i tried with array.length() it also throwing the same error. When i used the same with string_name.length() is working fine.
Why it is not working for an integer array?

The length of an array is available as
int l = array.length;
The size of a List is availabe as
int s = list.size();

I think you are confused between size() and length.
(1) The reason why size has a parentheses is because list's class is List and it is a class type. So List class can have method size().
(2) Array's type is int[], and it is a primitive type. So we can only use length

There is no method call size() with array. you can use array.length

Array's has
array.length
whereas List has
list.size()
Replace array.size() to array.length

public class Test {
int[] array = { 1, 99, 10000, 84849, 111, 212, 314, 21, 442, 455, 244, 554,
22, 22, 211 };
public void Printrange() {
for (int i = 0; i < array.length; i++) { // <-- use array.length
if (array[i] > 100 && array[i] < 500) {
System.out.println("numbers with in range :" + array[i]);
}
}
}
}

we can find length of array by using array_name.length attribute
int [] i = i.length;

Integer Array doesn't contain size() or length() method. Try the below code, it'll work. ArrayList contains size() method. String contains length(). Since you have used int array[], so it will be array.length
public class Example {
int array[] = {1, 99, 10000, 84849, 111, 212, 314, 21, 442, 455, 244, 554, 22, 22, 211};
public void Printrange() {
for (int i = 0; i < array.length; i++) {
if (array[i] > 100 && array[i] < 500) {
System.out.println("numbers with in range" + i);
}
}
}
}

Related

How to change an integer array within a method

I am having an issue with a fill-in-the-code digital textbook problem. All the code is permanent and cannot be changed, so the problem can only be solved by using the area that states //Write code here.
The problem asks to implement the removeOdd method.
import java.util.Arrays;
public class RemoveTester
{
public static int removeOdd(int[] values, int size)
{
//Write code here
}
public static void main(String[] args)
{
int[] a = { 22, 98, 95, 46, 31, 53, 82, 24, 11, 19 };
int sizeBefore = 8;
int sizeAfter = removeOdd(a, sizeBefore);
System.out.print("a: [ ");
for (int i = 0; i < sizeAfter; i++)
{
System.out.print(a[i] + " ");
}
System.out.println("]");
System.out.println("Expected: [ 22 98 46 82 24 ]");
int[] b = { 23, 97, 95, 45, 31, 53, 81, 24, 11, 19 };
sizeBefore = 7;
sizeAfter = removeOdd(b, sizeBefore);
System.out.print("b: [ ");
for (int i = 0; i < sizeAfter; i++)
{
System.out.print(b[i] + " ");
}
System.out.println("]");
System.out.println("Expected: [ ]");
}
}
The way I tried to implement removeOdd is by doing:
int evenCount = 0;
for(int i = 0; i<size; i++){
if(values[i]%2==0){
evenCount++;
}
}
int[] newValues = new int[evenCount];
int newCount =0;
for(int i = 0; i<evenCount; i++){
if(values[i]%2==0){
newValues[newCount] = values[i];
newCount++;
}
}
values = newValues;
return evenCount;
When the program is compiled and ran, main prints the beginning of the original a or b arrays instead of only the even elements in a or b. I cannot find a way to alter the original arrays within the method removeOdd into the new arrays with only their even elements. I can't think of any other way to do this either. Any help would be greatly appreciated!
The other answers give a good description of what the problem is with your overall approach...that is, why your results don't make it back to the calling method.
If your code were otherwise correct, you could use it as is and just copy the result back into the original array at the end. As it is, you had one flaw in your logic. So if you fix that flaw, and then do the copy at the end, you should get the correct result:
public static int removeOdd(int[] values, int size)
{
int evenCount = 0;
for(int i = 0; i<size; i++){
if(values[i]%2==0){
evenCount++;
}
}
int[] newValues = new int[evenCount];
int newCount =0;
for(int i = 0; i<size; i++) { // <- Need to iterate over the entire input array
if(values[i]%2==0){
newValues[newCount] = values[i];
newCount++;
}
}
for (int i = 0 ; i < evenCount ; i++) // <- now copy your result to the original array
values[i] = newValues[i];
return evenCount;
}
Rather than creating an extra array to temporarily hold the even values, you can use the same logic to copy into the original array directly:
public static int removeOdd(int[] values, int size)
{
int newCount =0;
for(int i = 0; i<size; i++) {
if(values[i]%2==0){
values[newCount] = values[i];
newCount++;
}
}
return newCount;
}
Because Java is pass by value and not pass by reference, setting the value of the values argument will not change the value of the a variable.
What you have to do is remove all the odd elements from the array and shift the remaining even elements to the left so that the actual resultant form of a looks like this:
{22, 98, 46, 82, 24, 0, 0, 0, 0, 0}
As #Geoff pointed out Java is pass by value, which means when you pass your array as an argument, what you get inside the method is a reference to the array object which is different from the original reference int[] a you have inside your main method (the caller). Therefore, when you do values = newValues; you are pointing that new reference which used to point to the same object as int[] a to the array object newValues points to, thereby not updating the original array a but actually losing any reference to it.

Alternative ways to find Matrix min max using Java

package myArray;
// https://github.com/javadevelopcom/ArrayVsArrayList/blob/master/src/myArray/MatrixMinMax.java
public class MatrixMinMax {
public static void matrixMinMax() {
System.out.println("Matrix is a rectangular array of numbers, symbols, or expressions:" + "\n");
int[][] matrix = {
{10, 10, 10, 10, -10},
{20, 20, 20, -20, 20},
{30, 30, -30, 30, 30},
{40, -40, 40, 40, 40},
{-50, 50, 50, 50, 50}};
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix.length; j++) System.out.print(matrix[i][j] + " ");
System.out.println();
}
int min = matrix[0][0];
int max = matrix[0][0];
for (int[] ints : matrix) {
for (int i : ints) {
if (i < min) {
min = i;
}
if (i > max) {
max = i;
}
}
}
System.out.println("MIN: " + min);
System.out.println("MAX: " + max);
}
}
Matrix Array min max, Two-dimensional array
Although this is mere speculation, depending on overall context, it would be possible not to search maximum and minimum in the actual data member
int[][] matrix
but use some custom method to set entries; this method would perform some check against additional members
int maximum = Integer.MIN_VALUE;
int minimum = Integer.MAX_VALUE;
and replace them if necessary. Such a method could be implemented as follows, and maximum and minimum would be accessible in the members above.
void setEntry(int i, int j, in value)
{
matrix[i][j] = value;
minimum = Math.min(value, minimum);
maximum = Math.max(value, maximum);
}
However, this approach basically would trade the time for searching the matrix for time setting up the matrix entries.
i think you can't do better then O(n^2) ; since the numbers are not sorted , or do not have any particular property (like all of them fit into a certain range, for example), you must access every single number, to make sure if it does/doesn't modify the value of the existing maximum/minimum. accessing all the numbers gives n^2 operations
One of the approach is to convert a two dimensional array to 1D list and use Stream API to get the min and max value.
We would have use Integer array as against int array in the above code. Consider the following implementation. The number of lines of code is decreased.
Integer[][] matrix = {
{10, 10, 10, 10, -10},
{20, 20, 20, -20, 20},
{30, 30, -30, 30, 30},
{40, -40, 40, 40, 40},
{-50, 50, 50, 50, 50}};
List<Integer> list = new ArrayList<Integer>();
for (Integer[] array : matrix)
list.addAll(Arrays.asList(array));
int max = list.stream().max((p1, p2) -> p1.compareTo(p2)).get().intValue();
int min = list.stream().min((p1, p2) -> p1.compareTo(p2)).get().intValue();
System.out.println("MIN: " + min);
System.out.println("MAX: " + max);
This isn't exactly the answer to the question but I think it sheds some light and gives some theoretical improvement.
If you want a O(n) complexity time, you should change you nested iteration for-loop:
//in O(n^2)
for (int[] ints : matrix) {
for (int i : ints) {
if (i < min) {
min = i;
}
if (i > max) {
max = i;
}
}
}
To something like:
for(i = 0; i<(X*Y); i++)
In you case X = 5,Y = 5; and then iterate.
Or you can easilly use lambdas to find the min and max of your array like below :
public int getTheMaxOfRow(int matrix[][], int row) {
return Arrays.stream(matrix).skip(row).limit(1).flatMapToInt(d -> Arrays.stream(d)).max().getAsInt();
}
public int getTheMinOfRow(int matrix[][], int row) {
return Arrays.stream(matrix).skip(row).limit(1).flatMapToInt(d -> Arrays.stream(d)).min().getAsInt();
}

How do I pass int values from one method to another

I'm trying to find the lowest time in minutes of the array int [] times, but I can't figure out how to make the second method work; I'm not getting any output.
public static void main(String[] arguments) {
String[] names = { "Elena", "Thomas", "Hamilton", "Suzie", "Phil",
"Matt", "Alex", "Emma", "John", "James", "Emily", "Daniel",
"Neda", "Aaron", "Kate" };
int[] times = { 321, 273, 278, 329, 445, 402, 388, 275, 243, 334, 412,
393, 299, 343, 317, 265 };
for (int i = 0; i < names.length; i++)
System.out.println(names[i] + ":" + times[i]);
}
I don't know what it's missing but i know i should get the lowest time in minutes: which is 243 (int [] times). I "believe" i need to pass the int time values from the first method to the second method...since i feel the second method array is empty. However, that, i don't know how to do. Help?
public static int getMinIndex(int[] values) {
int minValue = Integer.MAX_VALUE;
int minIndex = -1;
for (int i = 0; i < values.length; i++)
if (values[i] < minValue) {
minValue = values[i];
minIndex = i;
}
return minIndex; //not returning anything.
}
The logic of your program is:
1. Declaring an array of names.
2. Declaring an array of times.
3. Writing the names and times through a loop to the console.
You also wrote a method to retrieve the minimum value within an int array,
but you did not include that in your program, which starts from the first line of the main method.
So the first question would be, where would you like to use the minimum value.
and the second question would be, what would you like to do with the minimum value.
Suppose you want to show the min value on the console,
simply write:
System.out.println(getMinValue(times));
This way the method's return value is passed to the static method of System.out as an argument, suppose you want to do something else, pass it to another method that accepts int arrays.
Write this in your main method
int min_index = getMinIndex(times);
You forget to call method. Here min_index contains the integer value that you have to return from the method.
First, I would suggest you really want a getMinValue(int... arr)
public static int getMinValue(int... values) {
// Handle null and the empty array
if (values == null || values.length < 1) {
return -1;
}
// start at the first element
int minValue = values[0];
for (int i = 1; i < values.length; i++) {
if (values[i] < minValue) {
minValue = values[i];
}
}
// return the minimum value
return minValue;
}
Then you would call it with
public static void main(String[] args) {
System.out.println(getMinValue(4, 0, 2, 3));
int[] arr = { 5, 6, 7, 8, 3, 2 };
System.out.println(getMinValue(arr));
}
Output is
0
2

Reverse order of single dimensional array in Java [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How do I reverse an int array in Java?
I need to reverse the order of the given numbers in the array without using a temp.
public class Reverse
{
public static void main (String[] args)
{
int[] num = { 12, 34, 50, 67, 88 }, cl, cl2;
for (i=0; i < a.length; i++)
{
cl = a[i];
cl2 = a[(a.length - 1 )-1];
System.out.println (cl1 + " " + cl2);
}
}
}
Since it only seems that you're printing the values out, you can iterate over your array backwards.
for(int i = a.length - 1; i >= 0; i--) {
// relevant code here
}
you can use Collections#reverse to inline a reverse sort of the integer array,
Collections.reverse(Arrays.asList(num));
The answers given are perfect. But i just added another answer in case if you want to store the reverse array into the original array without using any temp. use this.
public class Reverse
{
public static void main (String[] args)
{
int[] a = { 12, 34, 50, 67, 88 };
int i, j;
for (i = 0, j = a.length - 1; i < j; i++, j--)
{
a[i]=a[i]+a[j];
a[j]=a[i]-a[j];
a[i]=a[i]-a[j];
}
}
}

Quicksort in Java

I'm supposed to do a quicksort algorithm in java to sort the array {50, 20, 65, 30, 75, 25, 90}. Here is what I have so far:
public class QuickSort {
public static int partition(int arrayName[], int down, int up){
int i = down, j = up;
int temp;
int pivot = arrayName[(down + up) / 2];
while (i <= j){
while (arrayName[i] < pivot)
i++;
while (arrayName[j] > pivot)
j--;
if (i <= j){
temp = arrayName[i];
arrayName[i] = arrayName[j];
arrayName[j] = temp;
i++;
j--;
}
}
return i;
}
public static void main(String[] args) {
int [] arrayName = {50, 20, 65, 30, 75, 25, 90};
System.out.println(partition(arrayName, down, up));
}
}
I'm getting an error on the print statement (seem to have a lot of trouble with these) that says down and up cannot be resolved to variables. How can I fix it so I can successfully print the sorted list?
It's because you haven't defined any variables named down and up in your main method. You should specify values instead of those names.
Your partition method returns an int. Instead, change your method body so that it returns the newly sorted array (and make sure you change the return type in the method declaration too, else you'll get an error). Furthermore, you need to define up and down in the main method.
For instance:
public static int[] partition(...)
{
...
return arrayname;
}
Edit: furthermore, you may need to use Arrays.toString() to output the array correctly (it's been a while since I used Java). eg:
System.out.println(Arrays.toString(partition(arrayName, up, down)));
you are getting index out of bound ,
because up and down are non initialized and in java it makes them 0
so down goes at j :
while(arrayName[j]<pivot){ //<--- this will thow exception as j starts at 0
j--;
which leads to -1 and accessing the array at arrayName[-1] is out of bound.

Categories