我对java很陌生,我正在尝试创建一个简单的方法来对输入的数字进行升序或降序排序。但是,有一个问题,我无法输入重复的值。有没有办法获取数组中某一项的key?
我的代码:
import java.io.Console;
public class TestSort {
public static void main(String args[]) {
Console c = System.console();
if (c == null) {
System.err.println("No console.");
System.exit(1);
}
System.out.println("TESTSORT.java");
System.out.println("-------------");
System.out.println("Type in a set of numbers here:");
String in = c.readLine();
System.out.println("(A)scending or (D)escending");
String ad = c.readLine();
boolean d = false;
if(ad.equals("a")) d = false;
else if(ad.equals("d")) d = true;
else {
System.out.println("Invalid Input.");
System.exit(1);
}
String[] in2 = in.split(" ");
int[] x = new int[in2.length];
int count1 = 0;
for(String val : in2)
x[count1++] = Integer.parseInt(val);
int[] a = new int[x.length];
int count = 0;
for(int y : x) {
for(int z : x) {
// if index of y equals index of z continue
if(z < y) count++;
}
a[count] = y;
count = 0;
}
if(d) {
int[] arr3 = new int[a.length];
int length = a.length;
for(int b : a) arr3[--length] = b;
for(int b : arr3) System.out.println(b);
} else
for(int b : a)
System.out.println(b);
}
}
这个程序只是计算比自己小的其他数字的个数,但不包括自己。但是,它与具有相同值的其他数字没有区别。
如果有帮助,我们将不胜感激。
谢谢。
最佳答案
要获取数组的某个值的索引,您必须循环遍历该数组。但是,如果有多个条目具有相同的值,则此方法将不起作用(无需修改)
int indexVal = -1;
int inputValue; // This is your input vlaue you are trying to find
for(int i = 0; i < array.length ; i++)
{
if (array[i] == inputValue)
{
indexVal = i;
break;
}
}
您可能还想查看Array.sort用于内置数组排序
关于java - 如何获取某个数组元素的键?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18303748/