簡體   English   中英

Java掃描器陣列

[英]Java Scanner Array

我在用Java遇到麻煩。 我需要掃描數字(例如: 1 3 4 2 5 6 7 )並將其放入數組。 問題是我不知道要多久。 是否可以使用命令來確定放入掃描儀中的數字的長度?

如果您不想使用ArrayList作為解決方法,我建議先讀取整行,然后拆分以獲取長度和單個值:

   String line = scanner.nextLine();
   String[] values = line.split(" ");
   int[] intValues = new int[values.length];
   int indx = 0;
   for(String value:values){
     intValues[indx++] = Integer.parseInt(value);
   }

編輯 :第二種方法:

   List<Integer> numList = new ArrayList<Integer>();
   int number = 0;
   while (number != -1) {
      System.out.println("Enter a positive integer value (or -1 to stop): ");
      number = Integer.parseInt(in.nextLine());
      if (number != -1){
        numList.add(number);
      }
   }
   in.close();

   Integer[] numArray = numList.toArray(new Integer[numList.size()]);

EDIT2:照顧同一行中的多個數字並在空行處終止

List<Integer> numList = new ArrayList<Integer>();
while(true) {
   System.out.println("Enter a positive integer value (or -1 to stop): ");
   String line = in.nextLine();
   if(line.length() <1){
      break;
   }
   String [] numbers = line.split(" ");
   for(String num: numbers){
          numList.add(Integer.parseInt(num));
   }
 }
 in.close();

 Integer[] numArray = numList.toArray(new Integer[numList.size()]);

如果需要可變大小的集合,請使用ArrayList

ArrayList<Integer> lst = new ArrayList<Integer>();
lst.add(scanner.getInt());

您可以使用ArrayList 只需將其填滿,最后將其轉換為整數數組即可。 甚至更好,保留清單並使用該清單。

Scanner in = new Scanner(System.in);

ArrayList<Integer> intList = new ArrayList<Integer>();
while (true) {
  System.out.println("Enter a positive integer value (or -1 to stop): ");
  int number = in.nextInt();
  if (number < 0) break;
  intList.add(number);
}
// just use this last line if you really want an array. Work with the list instead if possible.
Integer[] yourFinalArray = intList.toArray(new Integer[0]);

如果您使用Google Guava庫( https://code.google.com/p/guava-libraries/ ),則可以說:

String numbers="1 3 4 2 5 6 7";
Splitter.on(" ").split( numbers );

這給你一個迭代。 如果您堅持要獲取字符串數組,則可以說:

Iterables.toArray(Splitter.on(" ").split( numbers ), String.class)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM