数组输入似乎只接受最后一个输入 [英] Array input only seems to take the last input
问题描述
导入java.util.Scanner;
import java.util.Arrays;
公共类Sort_Array {
public static void main(String [] args){
int a;
Scanner sc = new Scanner(System.in);
System.out.println(输入数组大小);
int n = sc.nextInt();
int [] arr_num = new int [n];
System.out.println(在数组中输入整数);
for(int i:arr_num)
{
arr_num [i] = sc.nextInt();
}
System.out.println(排序前的数组---- \n);
for(int j:arr_num)
{
System.out.print(j +,);
}
System.out.println( \n);
Arrays.sort(arr_num);
System.out.println(排序后的数组---- \n);
for(int k:arr_num)
{
System.out.print(k +,);
}
}
}
输出
输入数组的大小
2
输入整数数组
5
6
排序前的数组----
6,0,
排序后的数组----
0,6,
System.out.println(输入数组大小);
int n = sc.nextInt();
int [] arr_num = new int [n];
在这里,您可以看到经过数组大小即2时的实际情况。 p>
arr_num初始化为0值(这是int对象的默认值)
0 0
此后,您对每个都使用了 >循环。
基本上说,当您看到冒号(:)时,将其读为 in。因此,基本上,您正在读取array_num中每个为0 0的int i。
for(int i:arr_num )
{
arr_num [i] = sc.nextInt(); // arr_num [0] = sc.nextInt();
//再次,arr_num [0] = sc.nextInt();
}
所以这就是你得到的原因
6,0
因为<您输入的em> 5 现在在arr_num [0]处再次由 6 代替。而第二个0仍然停留在arr_num [1]。
如其他答案所示,请使用其他循环。并了解有关每个循环的更多信息。
import java.util.Scanner;
import java.util.Arrays;
public class Sort_Array {
public static void main(String[] args) {
int a;
Scanner sc = new Scanner(System.in);
System.out.println(" Enter size of Array ");
int n = sc.nextInt();
int[] arr_num = new int[n];
System.out.println(" Enter the integers in the Array");
for(int i : arr_num)
{
arr_num[i] = sc.nextInt();
}
System.out.println(" Array before sorting ----\n");
for(int j : arr_num)
{
System.out.print(j+",");
}
System.out.println("\n");
Arrays.sort(arr_num);
System.out.println(" Array after sorting ----\n");
for(int k : arr_num)
{
System.out.print(k+",");
}
}
}
Output
Enter size of Array
2
Enter the integers in the Array
5
6
Array before sorting ----
6,0,
Array after sorting ----
0,6,
System.out.println(" Enter size of Array ");
int n = sc.nextInt();
int[] arr_num = new int[n];
Here you see what is really happening when you have passed the size of the array say, 2
arr_num is getting initialized with 0 value ( which is the default value for int object)
0 0
After this, you have used the for each loop. Which basically says, When you see the colon (:) read it as "in." So basically, you are reading each int i in array_num which are 0 0.
for(int i : arr_num)
{
arr_num[i] = sc.nextInt(); //arr_num[0] = sc.nextInt();
//again, arr_num[0] = sc.nextInt();
}
So this is the reason you are getting
6,0
because 5 which was inputted by you is now replaced by 6 again at arr_num[0]. while 2nd 0 still stays which is at arr_num[1].
As other answers suggest, use a different loop. And read more about for each loop.
这篇关于数组输入似乎只接受最后一个输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!