0

I am Java Beginner. I made a class and a method which is to return the minimum number in the array. But I can't figure out why it is not working well.

Below is Code.

package array;
import java.util.Scanner;

class Value {
    public static int minValue(int[] arr) {
        for(int e : arr) {
            if(arr[0] > e) {
                arr[0] = e;
            }
        }
        return arr[0];
    }
}
public class ArrayTest {

public static void main(String[] args) {
    int[] arr = new int[5];
    System.out.print("Input Number : ");
    Scanner sc = new Scanner(System.in);

    for(int e : arr) {
        e = sc.nextInt();
    }

    System.out.println("min : " + Value.minValue(arr));
}

The result is "min : 0 " What's the problem with my code???

JKRT
  • 1,179
  • 12
  • 25
David.J
  • 3
  • 2
  • 4
    `e = sc.nextInt();` You never add `e` to the array. – 001 Oct 17 '18 at 18:48
  • Look at this: https://stackoverflow.com/questions/18169703/for-each-loop-can-we-populate-an-array. You have to use the normal for version and not the for-each version for populating your array – mettleap Oct 17 '18 at 18:50
  • Thank you everybody. Now, I can know the reason. :D – David.J Oct 17 '18 at 19:00

3 Answers3

1

you have to change only the method of taking input nothing else, I have added a right one you can use this.

  int i = 0;
  for (int e: arr) {
  arr[i] = sc.nextInt();
  i++;
  }
0

Ok let me try and run it down. You create an array of integers with length of 5 index, ask the user for 5 numbers, add these numbers to the array arr as the user enters them. I see that in the for loop

for(int e : arr) {
    e = sc.nextInt();
}

e is being assigned the user input but it is not passing that into the array arr. Looks like you need to add a statement to pass/add the user input into the array.

-2

i think this may help you

    public static int minValue(int[] arr) {
        int min = Integer.MAX_VALUE;
        for(int e : arr) {
            if(e < min) {
                min = e;
            }
        }
        return min;
    }

and also change this

 for(int i = 0; i < arr.length; i++) {
    arr[i] = sc.nextInt();
 }
Pandey Amit
  • 657
  • 6
  • 19