Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiplying, smallest number and the position of that smallest number

Tags:

java

I have an assignment and I've already written the first two parts, I just cant figure out how to do the finding of the smallest number. I should mention that it is in jFrame (gui). It's supposed to look like this:

enter image description here

Lets say i have a list of numbers (10 5 8 7 4 9) and I wanna know at which position is the number 7. How do I do that? I've been stuck on this for the last hour. :/ here's what I have so far:

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
    String s = jTextField1.getText();
    String[]divide = s.split(" ");
    int[] number = new int[10];
    int sum = 1;
    for(int i = 0; i<10; i++)
    {
        number[i] = Integer.parseInt(divide[i]);
        sum = sum * number[i];
    }
    jTextField2.setText(Integer.toString(sum));
}                                        

private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {                                         
   String s = jTextField1.getText();
    String[]divide = s.split(" ");
    Arrays.sort(divide);
    jTextField3.setText(divide[0]);
}                                        

private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {                                         


    public static int findMin(ArrayList<Integer> n)
{
int minValue = Integer.MAX_VALUE; 
int minIndex = -1;
for(int i = 0; i < n.size(); i++){
    if(n.get(i) < minValue){
        minIndex = i;
    }
}
return minIndex;
like image 238
unreal Avatar asked Dec 07 '25 00:12

unreal


1 Answers

When you find the index of the minimum value, you should update the minValue.

public static int findMin(ArrayList<Integer> n) {
    for(int i = 0; i < n.size(); i++){
        if(n.get(i) < minValue){
            minIndex = i;
            minValue = n.get(i);   //Update here
        }
    }
    return minIndex;
}

Your code is always comparing the i-th element with int minValue = Integer.MAX_VALUE; that you never change.

Adding it below the if statement will update it, and you'll get the desired result.

like image 163
Maroun Avatar answered Dec 08 '25 15:12

Maroun