【问题标题】:I have written a code for finding the smallest number from the array but it is not giving proper output我已经编写了一个用于从数组中查找最小数字的代码,但它没有给出正确的输出
【发布时间】:2021-07-01 09:00:51
【问题描述】:

这是我的代码:

import java.util.*;

class minmax{
public static int getSmallest(int[] a, int n){
    Arrays.sort(a);
    return a[0];
}
public static void main(String args[]){
    
    int[] a = new int[20];
    Scanner sc = new Scanner(System.in);
    int n = sc.nextInt();
    
    System.out.println("Enter Array Elements: ");
    for(int i=1; i < n ;i++){
        a[i] = sc.nextInt();
    }
    System.out.println("Smallest: "+getSmallest(a,n));  
}
}

你能告诉我哪里出错了吗?

问题概述: 我必须从用户那里获取输入(数组元素和数组大小),然后从用户的输入中找到最小的元素。

输出: Output: Showing Smallest Number 0

【问题讨论】:

  • 数组中存储第一个元素的索引是多少?
  • int n 在这里做什么?您还没有使用该变量。
  • 因为在读取用户输入时没有为a[ 0 ] 赋值。因此,a[0] 始终为0
  • 你的错误是:你没有添加一点代码来循环数组并将内容打印到屏幕上,所以你可以看到那里有很多零。这是一个基本的调试技巧(不使用实际的调试器,这对你来说可能有点过头了);如果您对数据有疑问,请让这些数据对您可见。

标签: java arrays element


【解决方案1】:

首先,您不会在接受数组元素输入的循环中从 0 迭代到 n

其次,数组的大小固定为 20,并且作为int[],因此数组的所有值都设置为0。因此,一旦您使用all elements &gt; 0n &lt; 20 对数组进行排序,那么0 将是数组中的最小元素。

    public static int getSmallest(int[] a, int n){
        Arrays.sort(a);
        return a[0];
    }

    public static void main(String args[]){
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();

        int[] a = new int[n]; // Create an array of only N elements
        System.out.println("Enter Array Elements: ");
        for(int i=0; i < n ;i++){ // Start from 0
            a[i] = sc.nextInt();
        }
        System.out.println("Smallest: "+getSmallest(a,n));
    }

【讨论】:

    【解决方案2】:
    import java.util.*;
    
    class Main{
     public static int getSmallest(int[] a, int n){
        Arrays.sort(a);
        return a[0];
    }
    
    public static int getBiggest(int[] a, int n){
        Arrays.sort(a);
        return a[n-1];
    }
    
    public static void main(String args[]){
    
      System.out.println("Enter Number of Elements: ");
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int[] a = new int[n];
    
      System.out.println("Enter Array Elements: ");
      for(int i=0; i < n ;i++){
        a[i] = sc.nextInt();
      }
     System.out.println("Smallest Element: "+getSmallest(a,n));
     System.out.println("Biggest Element: "+getBiggest(a,n));
     }}
    

    谢谢大家?,我阅读了所有的 cmets 和回答我问题的人,我明白我犯了什么错误,最后,我写了这段代码,我知道它看起来很丑,但它工作正常。?

    【讨论】:

      猜你喜欢
      • 2019-12-23
      • 2013-06-23
      • 1970-01-01
      • 1970-01-01
      • 2017-05-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-01
      相关资源
      最近更新 更多