【问题标题】:sorting(ascending order and descending order) [duplicate]排序(升序和降序)[重复]
【发布时间】:2016-03-03 22:01:23
【问题描述】:

有人可以帮助我使用数组继续此代码吗?这是示例输出 输入元素数(2-10):5 元素[1]:-3 元素[2]:0 元素[3]:10 元素[4]:2 元素[5]:7

Max Value is: 10
Min Value is: -3

Ascending order: -3 0 2 7 10
Descending order: 10 7 2 0 -3

我只有这个代码。

import java.util.Scanner;

public class Array1 {
    public static void main(String[] args) {
        Scanner n = new Scanner(System. in );
        int num[] = new int[];
        int ne = 0;
        int e = 0;
        System.out.print("Enter Number of Elements(2-10): ");
        ne = n.nextInt();
        for (int x = 1; x <= ne; x++) {
            System.out.print("Element[" + x + "]: ");
            e = n.nextInt();
        }
    }
}

这个的输出是:

Enter number of element(2-10): 5
Element[1]: -3
Element[2]: 0
Element[3]: 10
Element[4]: 2
Element[5]: 7

那我不知道怎么弄到其他人了。

【问题讨论】:

  • 您的代码存在一些缺陷。第一的。在您知道它将有多少项目之前,您不应该声明一个新的 int 数组。 (所以在 ne = n.nextInt(); 之后移动 int num[] = new int[]; 并使用 new int[ne] 声明一个包含“ne”项的数组。然后在你的 for 循环中你应该填充该数组。

标签: java arrays


【解决方案1】:

我可以分享逻辑,但不能分享代码。

用户输入的数字可以添加到数组中。
Arrays.sort()可以用于升序或降序排序。
参考:Arrays SortReverse order

【讨论】:

    【解决方案2】:
    • 将代码更改为下面

    1.) 首先获取用户输入以创建大小为 ne 的数组。

    2.) 使用大小 ne 初始化您的数组。

    3.) 在循环中,不断获取元素并将其放入数组中。

    public static void main(String[] args) {
            Scanner n = new Scanner(System.in);
    
            int ne = 0;
            int e = 0;
            System.out.print("Enter Number of Elements(2-10): ");
            ne = n.nextInt();
    
            int num[] = new int[ne];
    
            for (int x = 0; x < ne; x++) {
                System.out.print("Eneter element");
                num[x] = n.nextInt();
            }
    
            System.out.println("original " + num);
        }
    

    Sorting,请先尝试自己的帖子,然后发布

    【讨论】:

    • 谢谢。我会尝试。目前我没有 jcreator,这就是我在编写程序时遇到麻烦的原因。我需要手动执行
    猜你喜欢
    • 1970-01-01
    • 2012-11-08
    • 2023-03-07
    • 1970-01-01
    • 2015-03-09
    • 2017-11-16
    • 1970-01-01
    • 1970-01-01
    • 2020-10-12
    相关资源
    最近更新 更多