[英]java array using scanner
在我的程序中,我想使用Scanner
顯示一個數組,即用戶在運行時輸入數組值。
public class NameComparator {
public static void main(String args[]) {
Scanner sn = new Scanner(System.in);
int n = sn.nextInt();
System.out.println("the array size is" + n);
int[] a = new int[7];
for (int i = 0; i >= a.length; i++) {
a[i] = sn.nextInt();
System.out.println("the value of a[i]" + a[i]);
}
sn.close();
System.out.println("array values are");
}
}
在這里,我從Scanner
獲得了數組大小,然后使用for
循環獲取每個數組值,但是我不知道為什么數組塊沒有執行。 JVM只是跳過for
循環。 Scanner
效果很好
有幾個問題:
int[] a= new int[7];//<-- why hard coded?
int[] a= new int[n];// try, you already have array size from user
for(int i=0;i>=a.length;i++)//<-- condition fails, i is 0 for the first time
for(int i=0; i < a.length; i++)//try this
這個:
for(int i=0;i>=a.length;i++)
應該:
for (int i = 0; i < a.length; i++)
只要i
小於a.length
(即數組的大小),就想循環。 如果終止條件返回false
則for循環將退出(或跳過)。 由於您要使用0
初始化i
,因此i>=a.length
(即0 >= 7
)將立即為false
。
請注意,我寫的是i < a.length
而不是i <= a.length
。 數組大小當前設置為7
,因此有效索引為0
到6
。 如果您嘗試訪問索引7
則將獲得ArrayIndexOutOfBoundsException
。
而且您忘記了使用變量n
設置數組大小:
int[] a= new int[n];
仔細看看您的for循環。
for(int i=0;i>=a.length;i++)
請注意,您使用的是大於號。
由於i
等於0,長度a
必須是0,這個循環運行,而且我們已經知道,你宣布a
用7%的長度。
更改以下代碼
for(int i=0;i>=a.length;i++) with for(int i=0;i<a.length;i++)
條件應為<
而不是>=
也可以使用sn.hasNext()
簡化解決方案。
我會四處搜尋,因為有很多與此類似的問題。
無論如何,您有幾處錯誤。 您提示用戶輸入數組大小,然后將其扔掉並改用7:
int[] a= new int[7];
因此,應為:
int[] a= new int[n];
二 ,你的循環條件:
for(int i=0;i>=a.length;i++)
只要i 大於a,就將成立,只要a為正整數(因為i從零開始),就永遠不會發生。 因此,如果我們使用小於,則還應該記住數組的索引為零,因此,如果輸入值3,則只想填充索引0、1和2。
因此,應改為:
for(int i=0;i < a.length;i++)
最后,請記住提示用戶,即使這只是一種學習練習,也是一種好習慣。 將所有內容放在一起,您將獲得如下內容:
public static void main(String args[])
{
Scanner sn=new Scanner(System.in);
System.out.println("Please enter an array size:" );
int n=sn.nextInt();
System.out.println("the array size is "+ n);
int[] a= new int[n];
System.out.println("Please enter your " + n + "array values:");
for(int i=0;i < a.length;i++)
{
a[i]= sn.nextInt();
System.out.println("The value of a[" + i + "] is " + a[i]);
}
sn.close();
System.out.println("Array values are " );
for (int arrayValue : a)
System.out.println(" " + arrayValue);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.