P
P
Pavel2015-01-11 13:22:32
Java
Pavel, 2015-01-11 13:22:32

Java program to find smallest number?

A simple task that led me a little into a stupor.

public static void main(String[] args) {
    int a, b, c, d;
    int min = 0;
    a = 12;
    b = 22;
    c = 33;
    d = 11;
    
    if(a>b){
      min = b;
    }
    if(min>c){
      min = c;
    }
    if(min>d){
      min = d;
    }
    System.out.println("Наименьшее число "+min);
  }

The problem is that if the first if a>b does not work, then min will not be filled with a number and by default it will be 0 , therefore all subsequent manipulations are useless, min will always be 0.
If min is not assigned a default value, then the code will not work at all.
How to find the smallest number?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
S
Sergey Nalomenko, 2015-01-11
@mrusklon

int min = a;

T
timoo, 2015-01-11
@tomcat1911

1) Put the values ​​in an array
2) Walk through the array, remembering the minimums

min = array[0];
for (int i=1; i < array.length; i++) {
  if (array[i+1] < min)
    min = array[i+1]    
}

PS Correct me if anything, I do not write in Java.

A
asd111, 2015-01-12
@asd111

int[] numbers = {9,8,7,6,5,4,3,2,1} ;
int min = numbers[0];
for ( int n : numbers ) {
     min = min < n ? min : n;
}
System.out.println("Min = " + min);

And a cheating brake method in two lines:
int[] numbers = {9,8,7,6,5,4,3,2,1} ;
Arrays.sort(numbers);
int min = numbers[0];
System.out.println("Min = " + min);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question