[英]creating array with elements determined by user/input
嘗試創建一個數組,並希望元素變大而輸入將變大。 最終,它應該使用x數量的數字,放置在數組中,然后返回平均值。 但是首先,我需要弄清楚如何將元素的大小放置在數組中。
import java.util.Scanner;
import java.util.ArrayList;
//needs to be an array
public class statsv2
{
public static void main (String args[])
{
int[] a= new int[5];
Scanner sc=new Scanner(System.in);
System.out.println("Please enter numbers...");
for(int j=0;j<5;j++)
{
a[j]=sc.nextInt();
}
}
}
因此,我本質上希望那個“ 5”(出現兩次)是用戶不斷輸入新數字的次數
首先,使用yourArray.length
代替j<5
。
至於數組大小,這不能動態完成,您有三個選擇:
1)創建一個足夠大的數組,以使用戶不會超出它,您必須做一些額外的檢查才能在用戶輸入結束時停止。
2)使用ArrayList
,您可以將其動態添加到其中,然后在用戶輸入完數據以提取要處理的數組時調用“ toArray()”。
3)完全跳過該數組,並使用ArrayList
來保存和處理輸入。
數組的長度實際上不是動態的。 我要做的一件事是將所有數據放入數組列表之類的結構中,然后當您到達輸入的末尾時,將該結構轉換為數組。
這樣的事情會起作用。
import java.util.*;
import java.lang.Integer;
public class wut {
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<String>();
Scanner scan = new Scanner(System.in);
while (scan.hasNext())
{
list.add(scan.next());
}
//^D received.
int[] a = new int[list.size()];
for (int i = 0; i < list.size();i++)
{
a[i] = Integer.parseInt(list.get(i));
}
System.out.println(Arrays.toString(a));
}
}
輸出:
javac *.java
$ java wut
3
4
5
6
7
8
^D
[3, 4, 5, 6, 7, 8]
對於您要查找的輸入類型,請查看以下問題的答案: 如何使用Java Scanner測試空白行?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.