2015-10-28 55 views
1

如何输入长度可能不同的数组?输入是空间分隔和结束时我按下输入在java中输入未知大小的数组

public class ArrayInput { 
    public static void main(String args[]){ 
     ArrayList<Integer> al = new ArrayList<Integer>(); 
     Scanner sc = new Scanner(System.in); 
     while(){//what condition to use here? 
      al.add(sc.nextInt()); 
     } 
    } 
} 

一个例子是:

1 2 5 9 7 4 //press enter here to mark end of input 
+0

是否在同一行所有你的整数?如果是这样,只需从'Scanner'中读取一行即可。 –

+0

你可以参考http://www.big4future.com/2015/09/fast-io-with-java-good-for-online.html它为字符串,整数等 – Ansu

回答

1

阅读使用\\s+使用sc.nextLine()然后split()整行。这样,您不必担心输入大小(元素数量)。使用Integer.parseInt()将字符串解析为整数。

2

由于所有的输入是在一个单一的线,你可以读取整个行,然后将其拆分为整数:

String line = sc.nextLine(); 
String[] tokens = line.split(" "); 
int[] numbers = new int[tokens.length]; 
for (int i=0; i<numbers.length;i++) 
    numbers[i] = Integer.parseInt(tokens[i]); 
+5

'“\\小号各种方法+ “'而不是'”“'? – TheLostMind