【问题标题】:Array to input 100 numbers输入 100 个数字的数组
【发布时间】:2019-02-13 17:21:59
【问题描述】:

我需要允许用户准确输入 100 个数字,即 100 个输入,然后打印其中的最小数字。输入 100 行 .nextInt() 会非常低效,我认为我可以使用正好包含 100 个输入的数组,然后在完成后找到最小值并将其打印出来。但我不知道该怎么做,那么有什么简单的方法呢?谢谢

【问题讨论】:

  • for 循环,任何带计数器的循环......
  • @Antoniossss ,我从未使用过这些或知道那是什么,这就是我寻求帮助的原因

标签: java arrays input min


【解决方案1】:

你可以在没有数组的情况下做到这一点,让我们看看如何。

int smallest=Integer.MAX_VALUE;//assume smallest to be largest integer
for(int i=0;i<100;i++){
    int num=sc.nextInt();//this will run 100 times and hence will input 100 number
    if(num<smallest){//if number is smaller than smallest then num is smallest
       smallest=num; 
    }
}
System.out.println(smallest);

【讨论】:

    【解决方案2】:

    试试这个代码示例。 我在我的电脑上运行了它,它可以工作。

    import java.util.Scanner;
    
    
    public class HelloWorld
    {
    
      public static void main(String[] args)
      {
        int [] Numbers = new int[100];
        Scanner input = new Scanner (System.in);
    
        for (int x=0;x<100;x++){
            System.out.println("Enter Number");
            Numbers[x]= input.nextInt();
        }
    
        int min = Numbers[0];
    
        for (int x=1;x<100;x++){
          if (Numbers[x] < min){
            min = Numbers[x];
          }
        }
    
        System.out.println("The Min number is :"+min);
      }
    }
    

    希望这会有所帮助:-)

    【讨论】:

      【解决方案3】:

      你不需要数组,这个例子是使用递归函数/方法:

      import java.util.Scanner;
      
      public class Code{
      
          public static void main(String[]args){
              Scanner sc = new Scanner(System.in);
              int min = prompt(sc, 1, 5); /* prompts for 5 values, change as required */
              sc.close();
              System.out.printf("Minium value is: %d%n", min);
          }
      
          private static int prompt(Scanner sc, int count, int times){
              System.out.printf("Enter number %d of %d: ", count, times);
              int n = sc.nextInt();
              if(count == times){
                  return n;
              }
              return Math.min(n, prompt(sc, (1 + count), times));
          }
      }
      

      【讨论】:

        【解决方案4】:

        感谢您提出此问题,如其他答案中所述,无需任何数组即可完成,但如果您想使用数组,请将其声明为

        int arr[]=new int[100];   
        

        使用 for 循环在其中输入值,
        然后申请

        Arrays.sort(arr);   
        

        arr[0] 将是最小值元素。

        【讨论】:

        • 查看 www.javatpoint.com 了解任何基本的 java 参考资料,这是一个学习基本 java 的非常好的网站
        猜你喜欢
        • 1970-01-01
        • 2017-03-21
        • 1970-01-01
        • 1970-01-01
        • 2017-11-21
        • 2014-01-23
        • 1970-01-01
        • 2020-07-17
        • 1970-01-01
        相关资源
        最近更新 更多