我必須提示用戶輸入一個整數值并創建一個該大小的整數陣列,但我不確定如何使用值為 1…大小的 for 回圈填充它,并列印出陣列元素他們的指數。
這是程式的示例執行。用戶輸入以粗體顯示。
多大的陣列?5
0:1
1:2
2:3
3:4
4:5
這是我到目前為止所擁有的:
Scanner sc = new Scanner(System.in);
System.out.print("How large an array? ");
int i = sc.nextInt();
int arr [] = new int[i];
for (int j = 0; j < i; j ) {
System.out.print(arr[i] ": ");
}
uj5u.com熱心網友回復:
你的意思是這樣嗎?我不確定你的問題是否理解正確。
Scanner sc = new Scanner(System.in);
System.out.print("How large an array? ");
int i = sc.nextInt();
sc.close();
int[] arr = new int[i];
for (int j = 0; j < i; j ) {
arr[j] = j 1;
System.out.println(j ": " arr[j]);
}
uj5u.com熱心網友回復:
您必須先設定應該保存在陣列中的值,然后才能訪問它們。這不會自動發生。
修復你的代碼后,我想出了這個:
Scanner sc = new Scanner( System.in );
System.out.print( "How large should the array be? " );
int size = sc.nextInt();
int[] array = new int[ size ];
//fill array with values
for ( int i = 0; i < size; i )
array[ i ] = i 1;
//print values
for ( int i = 0; i < size; i )
System.out.println( i ": " array[ i ] );
它為輸入 5 生成以下答案:
0: 1
1: 2
2: 3
3: 4
4: 5
我希望這能幫助你進一步。
uj5u.com熱心網友回復:
如果你真的不需要陣列,你可以通過使用 Java 8 IntStreamrange 特性來更簡單:
public class Main {
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
System.out.print("How large an array? ");
int numbersCount = sc.nextInt();
List<Integer> numbers = IntStream.range(1, numbersCount 1)
.boxed()
.collect(Collectors.toList());
for (int i = 0; i < numbersCount; i ) {
System.out.println(i ": " numbers.get(i));
}
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/367546.html
上一篇:在BASH中使用嵌套for回圈運行2x3x6變數回圈
下一篇:Python中的行內迭代是什么?
