How do I pass int values from one method to another - java

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

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.

In an array of int's, how can I return the index corresponding to the lowest value? [duplicate]

This question already has answers here:
Finding the index number of the lowest value in an array
(4 answers)
Closed 3 years ago.
I've managed to find the lowest value in the array with my "lowest" variable, but im looking for the index which corresponds to the lowest value in the array. Any ideas?
public class Marathon {
public static void main(String[] args) {
String[] names = { "Elena", "Thomas", "Hamilton", "Suzie", "Phil",
"Matt", "Alex", "Emma", "John", "James", "Jane",
"Emily", "Daniel", "Neda", "Aaron", "Kate" };
int[] times = { 341, 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]);
}
lowesttime(names, times);
}
public static void lowesttime(String names[], int times[]) {
int lowest;
lowest = times[0];
for (int i = 1; i < times.length; i++) {
if (times[i] < lowest) {
lowest = times[i];
}
}
System.out.println(lowest);
// to access arrays names[?], times[?}
// System.out.println(names[lowest] + ": " + times[lowest]);
}
}
public static void lowesttime(String[] names, int[] times) {
Pair<Integer, Integer> min = IntStream.range(0, times.length)
.mapToObj(i -> new Pair<Integer, Integer>(i, times[i]))
.reduce(new Pair<>(-1, Integer.MAX_VALUE), (r, p) ->
r.getKey() == -1 || r.getValue() > p.getValue() ? p : r);
String minName = p.getKey() == -1 ? "nobody" : names[p.getKey()];
System.out.printf("Found minimum for %s at index %d, value %d%n",
minName, min.getKey(), min.getValue());
}
I wanted to show using a Stream:
IntStream.range(0, N) will give a stream of 0, 1, 2, ..., N-1. The indices.
mapToObj converts to a Stream<Pair<Integer, Integer>> where the pairs key is the index, and the pairs value is times[index].
reduce will start with an initial pair (-1, Integer.MAX_VALUE) as result,
and then for every pair in the stream whether a better minimum can be found.
Note you could just use a pair of name and time (Pair<String, Integer>); the index is not needed.
It here might be too advanced and circumstantial, but it is both very expressive and clean (using steps without needing local variables).
You can set a variable to the index of the element, instead of just getting the value of that element;
public static void lowesttime(String[] names, int[] times) {
int lowest;
int lowestIndex = 0;
lowest = times[0];
for (int i = 1; i < times.length; i++) {
if (times[i] < lowest) {
lowest = times[i];
lowestIndex = i;
}
}
System.out.println(lowest);
System.out.println(lowestIndex);
// to access arrays names[?], times[?}
// System.out.println(names[lowest] + ": " + times[lowest]);
}
If you already know your lowest value, you can use:
java.util.Arrays.asList(theArray).indexOf(lowestValue)

Longest sequence of same numbers in array list

I'm trying to execute this so that it prints out the longest sequence of the same number. I've just edited it but it's telling me to place a return statement . Here's my code:
public class A1Q3 {
private static int getLongestRun(int[] array){
int count = 1;
int max = 1;
for (int i = 1; i < array.length; i++) {
if (array[i] == array[i - 1]) {
count++;
} else {
count = 1;
}
if (count > max){
max = count;
}
}
public static void main(String[] args) {
int[] array = new int[]{5, 6, 6, 45, -2, -9, 56};
System.out.println(getLongestRun(array));
}
}
You are missing a closing parenthesis for the getLongestRun() function and a return statement. You want to return the max variable.
Also, instead of
System.out.println(count);
Try:
System.out.println(getLongestRun(array));
to actually use the function you made. Your function is still not correct, however. You are returning the current streak count, not the longest streak count. You correctly reset the count back to 1 after the streak ends, but you need another variable named something like max to store the total maximum in addition to the current streak.

How can I make an array without one number of the other array?

I am trying to make a code with two arrays. The second array has the same values of the first except for the smallest number. I have already made a code where z is the smallest number. Now I just want to make a new array without z, any feedback would be appreciated.
public static int Second_Tiny() {
int[] ar = {19, 1, 17, 17, -2};
int i;
int z = ar[0];
for (i = 1; i < ar.length; i++) {
if (z >ar[i]) {
z=ar[i];
}
}
}
Java 8 streams have built in functionality that can achieve what you're wanting.
public static void main(String[] args) throws Exception {
int[] ar = {19, 1, 17, 17, -2, -2, -2, -2, 5};
// Find the smallest number
int min = Arrays.stream(ar)
.min()
.getAsInt();
// Make a new array without the smallest number
int[] newAr = Arrays
.stream(ar)
.filter(a -> a > min)
.toArray();
// Display the new array
System.out.println(Arrays.toString(newAr));
}
Results:
[19, 1, 17, 17, 5]
Otherwise, you'd be looking at something like:
public static void main(String[] args) throws Exception {
int[] ar = {19, 1, 17, 17, -2, -2, -2, -2, 5};
// Find the smallest number
// Count how many times the min number appears
int min = ar[0];
int minCount = 0;
for (int a : ar) {
if (minCount == 0 || a < min) {
min = a;
minCount = 1;
} else if (a == min) {
minCount++;
}
}
// Make a new array without the smallest number
int[] newAr = new int[ar.length - minCount];
int newIndex = 0;
for (int a : ar) {
if (a != min) {
newAr[newIndex] = a;
newIndex++;
}
}
// Display the new array
System.out.println(Arrays.toString(newAr));
}
Results:
[19, 1, 17, 17, 5]
I think the OP is on wrong track seeing his this comment:
"I am trying to find out the second smallest integer in array ar[]. I
should get an output of 1 once I am done. The way I want to achieve
that is by making a new array called newar[] and make it include all
the indexes of ar[], except without -2."
This is a very inefficient way to approach this problem. You'll have to do 3 passes, Once to find to smallest indexed element, another pass to remove the element (this is an array so removing an element will require a full pass), and another one to find smallest one again.
You should just do a single pass algorithm and keep track of the smallest two integers,
or even better use a tree for efficiency. Here are the best answers of this problem:
Find the 2nd largest element in an array with minimum number of comparisons
Algorithm: Find index of 2nd smallest element from an unknown array
UPDATE: Here is the algorithm with OP's requirements,
3 passes, and no external libraries:
public static int Second_Tiny() {
int[] ar = {19, 1, 17, 17, -2};
//1st pass - find the smallest item on original array
int i;
int z = ar[0];
for (i = 1; i < ar.length; i++) {
if (z >ar[i]){
z=ar[i];
}
}
//2nd pass copy all items except smallest one to 2nd array
int[] ar2 = new int[ar.length-1];
int curIndex = 0;
for (i=0; i<ar.length; i++) {
if (ar[i]==z)
continue;
ar2[curIndex++] = ar[i];
}
//3rd pass - find the smallest item again
z = ar2[0];
for (i = 1; i < ar2.length; i++) {
if (z >ar2[i]){
z=ar2[i];
}
}
return z;
}
This grabs the index of the element specified in variable z and then sets a second array to the first array minus that one element.
Essentially this gives ar2 = ar1 minus element z
public static int Second_Tiny() {
int[] ar = {19, 1, 17, 17, -2};
int[] ar2;
int i;
int z = ar[0];
int x = 0;
for (i = 1; i < ar.length; i++) {
if (z >ar[i]){
z=ar[i];
x=i;
}
}
ar2 = ArrayUtils.remove(ar, x);
return(z);
}

How to find integer array size in 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);
}
}
}
}

Categories