So I’m trying to get a program that reads a file, with the length of the file as the first line. And then finds the index of the minimum and the maximum in the file. The annoying thing is, that for some reason, my findMin and findMax methods are not working. It seems as if they are bypassing the for loops. I’m sure I’m just making a silly mistake, but I can’t seem to pinpoint it.
import java.io.File;
import java.util.Scanner;
public class Driver00 {
public static int minpos;
public static int maxpos;
public static double min;
public static double max;
public static int numitems;
public static void main(String[] args) throws Exception {
Scanner infile = new Scanner(new File("data.txt"));
int numitems = infile.nextInt();
double[] array = new double[numitems];
for (int k = 0; k < numitems; k++) {
array[k] = infile.nextDouble();
}
infile.close();
int minPos, maxPos;
minPos = findMin(array);
maxPos = findMax(array);
System.out.println("Minimum value: " + minPos);
System.out.println("Maximum value: " + maxPos);
}
private static int findMin(double[] apple) {
for (int x = 0; x < numitems; x++)
// not activating
if (x == 1) {
if (apple[x] < apple[x - 1]) {
min = apple[x];
minpos = x;
} else {
min = apple[x - 1];
minpos = x - 1;
}
} else {
if (apple[x] < min) {
min = apple[x];
minpos = x;
}
}
return minpos;
}
private static int findMax(double[] banana) {
for (int x = 0; x < numitems; x++)
// not activating
if (x == 1) {
if (banana[x] > banana[x - 1]) {
max = banana[x];
maxpos = x;
} else {
max = banana[x - 1];
maxpos = x - 1;
}
} else {
if (banana[x] > max) {
max = banana[x];
maxpos = x;
}
}
return maxpos;
}
}
public static int numitems;isZEROthat is why your for loop is not executedWhy numitems ZERO?
Because the integer your are getting at
int numitems = infile.nextInt();statement will be assigned to method localnumitemsvariable not for the instance variable.