[英]Sorting an array in ascending order in java
I'm trying to solve a java question, where I have to sort the numbers in ascending orders. 我正在尝试解决一个Java问题,在这里我必须按升序对数字进行排序。 My code works, until I put a negative in integer in it. 我的代码有效,直到我在其中输入一个负整数。
import java.util.Scanner;
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int input = sc.nextInt();
int[] numbers = new int[input];
for (int i = 0; i < numbers.length; i++) {
int a = sc.nextInt();
numbers[a] += a;
}
for (int i = 1; i < numbers.length; i++) {
System.out.println(i + " " + numbers[i] / i);
}
}
}
I want to set the amount of numbers in the line 9 as input, but I face errors when I enter bigger values or negative integers. 我想将第9行中的数字设置为输入,但是当我输入较大的值或负整数时会遇到错误。 Any helps plz? 有帮助吗?
This is basically what I need to sort out: 这基本上是我需要解决的问题:
input: 输入:
5
-3
100
-1
-2
-1
output: 输出:
-3 1
-2 1
-1 2
100 1
Arrays.sort() is a built-in function to help you sort the array Arrays.sort()是一个内置函数,可帮助您对数组进行排序
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int input = sc.nextInt();
int[] numbers = new int[input];
for (int i=0; i <numbers.length; i++) {
int a = sc.nextInt();
numbers[i] = a;
}
sc.close();
Arrays.sort(numbers);
int temp=numbers[0];
int count=1;
for(int i=1; i<numbers.length; i++){
if(numbers[i]==temp){
count++;
}else{
System.out.println(temp + " " + count);
count=1;
temp=numbers[i];
}
}
System.out.println(temp + " " + count);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.