Calculate the smallest element in a list

0

Given a sequence of integers (read via Scanner ), determine the smallest of these values.

My code:

import java.util.Scanner;

public class MenorValorSequencia {

    public static void main (String args []) {

    Scanner sc = new Scanner (System.in);
    int [] variavel = new int [10];
    for (int i = 0; i<=9; i++) {
    variavel[i] = sc.nextInt();
    }

    int menorValor = 0;
        for (int i = 0; i<=9; i++) {
            if (variavel[i]<menorValor) {
                menorValor = variavel[i];
            }
        System.out.println (menorValor(i)); // erro: não pode achar variável menorvalor
        }
    }
}

Can the Java code for this problem be done like this?

Can someone please fix what's wrong?

    
asked by anonymous 16.07.2016 / 23:22

2 answers

5

It has three errors: the initial value must be the largest integer possible; you have to print the variable and not a function; and the impression should occur after the loop finishes and not inside it.

import java.util.Scanner;

class MenorValorSequencia {
    public static void main(String args[]) {
        Scanner sc = new Scanner(System.in);
        int[] variavel = new int[10];
        for (int i = 0; i <= 9; i++) {
            variavel[i] = sc.nextInt();
        }
        int menorValor = Integer.MAX_VALUE;
        for (int i = 0; i <= 9; i++) {
            if (variavel[i] < menorValor) {
                menorValor = variavel[i];
            }
        }
        System.out.println(menorValor);
    }
}

See working on ideone .

    
16.07.2016 / 23:35
2

The initial value of int menorValor = 0; is the problem, for this value to be changed, a negative value is required.

And here is not an array System.out.println (menorValor(i));

The correct one would be: System.out.println (menorValor);

    
16.07.2016 / 23:26