使用Java方法查找数组中最小int的位置
我编写了以下方法来查找数组中最小数字的位置/索引
private static int indexOfMin( int[] a, int cnt )
{
int loc = 0;//the variable that will hold the index position
int min = a[loc];//the variable that will compare the value of loc against its location
for (int i = 1; i < a.length; i++)
{
if (a[i] < min )//if value is less
{
min = a[i];// make value of i equal to min
loc = i; loc takes on value of the index of the value of min
}
}
return loc ;
}
它不返回最小int的位置,而是返回最后一个int的位置。如何找到最小int的位置并将其返回到int loc
进一步编辑: 这是整个计划。另外两种方法我还在研究中。所以不要理他们
public static void main (String[] args) throws Exception
{
final int CAP = 20; // capacity
Scanner infile = new Scanner( new File(args[0]) );
int[] arr = new int[ CAP ];
int count = 0;
while ( count < arr.length && infile.hasNextInt() )
{
arr[ count ] = infile.nextInt();
count++;
}
infile.close();
printArray( arr, count );
// this method is given to you as as. don't modity it
int minVal = minOf( arr, count );
System.out.println( "Smallest number is: " + minVal);
// YOU MUST WRITE THE DEFINITION (code) BELOW MAIN FOR indexOfMin METHOD
int indOfMin = indexOfMin( arr, count );
System.out.println( "Smallest number is located at index position: " + indOfMin );
// YOU MUST WRITE THE DEFINITION (code) BELOW MAIN FOR maxOf METHOD
int maxVal = maxOf( arr, count );
System.out.println( "Largest number is: " + maxVal);
// YOU MUST WRITE THE DEFINITION (code) BELOW MAIN FOR indexOfMax METHOD
int indOfMax = indexOfMax( arr, count );
System.out.println( "Largest number is located at index position: " + indOfMax );
} // END main
// GIVEN AS IS - DO NOT MODIFY
private static int minOf( int[] a, int cnt )
{
int min = a[0];
for ( int i=0 ; i<cnt ; i++ )
{
if (a[i] < min)
min = a[i];
}
return min;
}
// YOU WRITE DEFINTION OF indexOfMin
// returns the INDEX of the min value NOT the min value itself
private static int indexOfMin( int[] a, int cnt )
{
int loc = 0;
int min = a[loc];
for (int i = 1; i < a.length; i++)
{
if (a[i] < min )
{
min = a[i];
loc = i;
}
}
return loc ;
}
日期文件包含以下信息:
86 95 84 94 32 8 56 51 98 20 90 1 75 6 21
# 1 楼答案
为什么不使用
Arrays.sort()
并返回数组的第一个元素# 2 楼答案
印刷品:
4
这是绝对正确的,因为数组的索引以0开头
# 3 楼答案
第一种方法有效
你没有问题
您可能忘记了索引从0开始,因此将结果解释为错误
# 4 楼答案
根据你的评论和编辑,我认为你想要
那么为了验证,
# 5 楼答案
如上所述,您的第一段代码工作正常
java中的数组从索引=0开始
从外观上看,cnt应该是您要传递的数据数组的长度,它可以用作.length的替代品(尽管传递额外数据是非常不必要的)
在第二段代码中,在完成整个循环(可能)之前返回一个索引。一旦到达第一个小于[0]的项并返回该位置(在本例中可能发生在索引3处),此操作将停止
为便于将来参考,了解您正在测试的数据将对我们有所帮助
# 6 楼答案
第一个代码是正确的。您仍然可以删除从未使用过的cnt。第二个是绝对错误的
导入java。util。扫描仪
您要输入多少个数字:7
输入数字: 34 45 33 234 123 116 555
最小no的位置为:3
我希望这对你有帮助