[英]I'm unable to assign values to array index. I have to assign values to individual variables
[英]I'm unable to store values in array as it is showing error?
我必須從用戶輸入中獲取數組的大小並將其存儲,我還嘗試將數組 ac 中的值存儲到大小但是當我運行程序時,for 循環在顯示邊界異常錯誤后執行一次
import java.util.Scanner;
public class Odd {
int size;
int a[] = new int[size];
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter Size of array");
size = sc.nextInt();
for (int i = 0; i < size; i++) {
System.out.println("enter " + i + "th element");
a[i] = sc.nextInt();
}
System.out.println("your array is");
for (int i = 0; i < size; i++) {
System.out.print(a[i] + " ");
}
}
}
當你寫
public class Odd
{
int size;
int a[]=new int[size];
然后每當構造Odd
時,都會a
創建為一個數組,其大小等於size
的當前值,即 0。
當你再寫
size=sc.nextInt();
a
的大小不會更改為size
變量的新值。
您的代碼有幾處錯誤。
首先,static 方法 main 無法訪問 size 和 a,因為它們是實例變量。 您需要將它們設為 static 或在 main 方法中將它們設為局部變量。
第二,規模為零。 您在不知道用戶將輸入什么大小的情況下創建數組。 該數組的大小為零。
第三,您不需要可變大小,因為您實際上並沒有在其他任何地方使用它。
import java.util.Scanner;
public class Main{
public static void main(String[]args){
Scanner sc=new Scanner(System.in);
System.out.println("Enter Size of array");
int[] a = new int[sc.nextInt()];
for(int i=0;i<a.length;i++){
System.out.println("enter "+i+"th element");
a[i]=sc.nextInt();
}
System.out.println("your array is");
for(int i=0;i<a.length;i++){
System.out.print(a[i]+" ");
}
}
}
將數組初始化移動到 main 方法內部,因為創建數組時需要大小。
public class Odd {
static int size;
static int a[];
public static void main(String[]args){
Scanner sc=new Scanner(System.in);
System.out.println("Enter Size of array");
size=sc.nextInt();
a = new int[size];
for(int i=0;i<size;i++)
{
System.out.println("enter "+i+"th element");
a[i]=sc.nextInt();
}
System.out.println("your array is");
for(int i=0;i<size;i++)
{
System.out.print(a[i]+" ");
}
}
}
and here is the output
Enter Size of array
3
enter 0th element
1
enter 1th element
2
enter 2th element
3
your array is
1 2 3
創建數組時,size 的值默認為 0。這樣做以獲得更好的結果:
public class Odd
{
int size;
int a[];
public static void main(String[]args)
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter Size of array");
size=sc.nextInt();
a = new int[size];
然后無論你必須做什么,你都可以做......
您實際上並不需要這些成員變量。
import java.util.Scanner;
public class SizeArray {
public static void main(String[]args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter Size of array: ");
int size = sc.nextInt();
int a[] = new int[size];
for(int i = 0; i < size;i ++) {
System.out.print("enter "+ i +"th element: ");
a[i]=sc.nextInt();
}
System.out.println("your array is");
for(int i = 0; i < size; i++) {
System.out.print(a[i]+" ");
}
sc.close();
}
}
您可以只輸入 main function 而不是在創建后修改它們。
Output:
Enter Size of array: 4
enter 0th element: 1
enter 1th element: 2
enter 2th element: 3
enter 3th element: 4
your array is
1 2 3 4
順便說一句,請以更具可讀性的格式編寫您的代碼。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.