zoukankan      html  css  js  c++  java
  • Java程序设计基础 数组 练习

    通过以上两次学习,做了一次练习。

    练习1:输入10个数,不用排序求出最大值和次最大值。

     1 package exercise;
     2 import java.util.Scanner;
     3 public class Sort {
     4 
     5     public static void main(String[] args) {
     6         // TODO 自动生成的方法存根
     7         Scanner in = new Scanner(System.in);
     8         System.out.println("Please enter 10  numbers and end with a -1 input :");
     9         int input = in.nextInt();
    10         int[] numbers = new int[10];//定义并创建拥有10 个元素的数组
    11         int max = 0;
    12         int sec = 0;
    13         while(input != -1)//输入数组
    14         {
    15             for(int i = 0;i < numbers.length;i++)
    16             {
    17                 numbers[i] = input;
    18                 input = in.nextInt();
    19                 //System.out.print(numbers[i] + "  ");
    20             }
    21         }
    22         System.out.println("数组中的元素为:");
    23         for(int element:numbers)//foreach语句输出数组
    24             System.out.print(element + "  ");
    25         System.out.print("
    ");
    26         max = numbers[9];
    27         sec = numbers[8];
    28         if(numbers[0] > numbers[1])
    29         {
    30             max = numbers[0];
    31             sec = numbers[1];
    32         }
    33         else
    34         {
    35             max = numbers[1];
    36             sec = numbers[0];
    37         }
    38         for(int i = 2; i < numbers.length;i++)
    39         {
    40             if(numbers[i] > max)
    41             {
    42                 sec = max;
    43                 max = numbers[i];
    44             }
    45             else
    46             {
    47                 if(numbers[i] > sec)
    48                 {
    49                     sec = numbers[i];
    50                 }
    51             }
    52         }
    53         System.out.println("最大数为:" + max + "     其次为:" + sec);
    54     }
    55 }

    运行结果为:

    Please enter 10 numbers and end with a -1 input :
    5 20 40 60 85 95 93 71 83 62 -1
    数组中的元素为:
    5 20 40 60 85 95 93 71 83 62
    最大数为:95 其次为:93

  • 相关阅读:
    MYSQL学习笔记
    javascript30--day01--Drum kit
    jQuery--dataTable 前端分页与后端分页 及遇到的问题
    hexo博客
    js—数组那些事儿
    累死青蛙系列——青蛙跳台阶问题
    js—求数组中的最大最小值
    前端html,css考点
    doxygen 使用 教程 不含安装仅设置
    fatal error LNK1169: one or more multiply defined symbols found 终极解决方案
  • 原文地址:https://www.cnblogs.com/yuyang-gr/p/6681522.html
Copyright © 2011-2022 走看看