我的任务中有几个目标,我要读一个文件,我相信我做的正确,并从整数文件中,把它放到一个数组中。它不会让我编译代码,它会在最小的时候出现错误。那么,我该如何打印出min的方法?
public class jlrogers2 {
public static void reader(int[] arr) throws FileNotFoundException {
Scanner scanner = new Scanner(new FileReader("numbers.txt"));
int i = 0;
while(scanner.hasNextInt())
{
arr[i++] = scanner.nextInt();
}
}
public static int minnimum(int[] arr){
int smallest =arr[0];
for (int i = 1; i>arr.length; i++){
if (arr[i] > smallest)
{
smallest= arr[i];
System.out.println(smallest);
}
}
return smallest;
}
public static void main(String [] args) throws FileNotFoundException
{
Scanner in = new Scanner (System.in);
System.out.println("Enter 1 for max index value.\nEnter 2 for min index value.\nEnter 3 to search for an index value.\n"
+ "Enter 4 for display all index's\nEnter 5 for numbers in a range.\nEnter 6 to exit menu. ");
int number = in.nextInt();
if(number==6){
System.out.println("Thank you for being awesome");
}
if (number==5){
System.out.println(minnimum(smallest)) // here is my issue }
}
}
答案 0 :(得分:4)
将for (int i = 1; i>arr.length; i++)
更改为for (int i = 0; i<arr.length; i++)
你找到最小的逻辑也是错误的。实际上你找到了最大的。
找到最小的把它当作
在if(arr[i] < smallest )
循环中 for
将主要内容更改为
public static void main(String [] args) throws FileNotFoundException
{
Scanner in = new Scanner (System.in);
System.out.println("Enter 1 for max index value.\nEnter 2 for min index value.\nEnter 3 to search for an index value.\n"
+ "Enter 4 for display all index's\nEnter 5 for numbers in a range.\nEnter 6 to exit menu. ");
int number = in.nextInt();
int arr[] = new int [200];//change this according to the requirement
if(number==6){
System.out.println("Thank you for being awesome");
}
if (number==5){
reader(arr);
System.out.println(minnimum(arr));
}
}
答案 1 :(得分:0)
您的代码似乎存在许多问题: -
- &gt;首先,其他人已将更改for (int i = 1; i>arr.length; i++)
指向for (int i = 1; i<arr.length; i++)
- &GT;使用的变量int smallest
不是类级变量,也不会在main()
- &GT;方法minimum()
永远不会从main调用,方法reader()
似乎也不会被调用
- &GT;使用后关闭扫描仪,在方法结束时调用scanner.close()
进行一些更改: -
- &GT; main()
现在看起来像: -
public static void main(String [] args) throws FileNotFoundException
{
int[] arr=new int[100];
reader(arr);//call this to populate arr[]
Scanner in = new Scanner (System.in);
System.out.println("Enter 1 for max index value.\nEnter 2 for min index value.\nEnter 3 to search for an index value.\n"
+ "Enter 4 for display all index's\nEnter 5 for numbers in a range.\nEnter 6 to exit menu. ");
int number = in.nextInt();
if(number==6){
System.out.println("Thank you for being awesome");
}
if (number==5){
System.out.println(minnimum(arr));
}
in.close();
}
答案 2 :(得分:0)
要找到需要更改循环的最小元素,请执行以下操作:
for (int i = 1; i < arr.length; i++)
{
if (arr[i] < smallest)
{
smallest = arr[i];
}
}