2016-03-02 86 views
1
Scanner s = new Scanner(System.in); 
List<Integer> solutions = new LinkedList<>(); 
int o = 0; 

while (o != 10) {  // I want to read 2 numbers from keyboard 
    int p = s.nextInt(); // until send and enter, this is where is my 
    int c = s.nextInt(); //doubt 
    int d = p + c; 
    solutions.add(d); 
    o = System.in.read(); 
} 

Iterator<Integer> solution = solutions.iterator(); 
while (solution.hasNext()) { 
    int u = solution.next(); 
    System.out.println(u); 
} 

我的問題是,我怎麼能發送一個輸入結束循環?因爲System.in.read()接受所述第一數量,如果我把另一個2號和實施例可以是,停止鍵盤輸入?

條目:

2 3(輸入)讀2號和總結

1 2 (輸入)讀2號和總結

(進入),並在這裏結束循環因爲進入並沒有數字並給出瞭解決方案

退出:

我不知道我UF

+0

將'u'值打印到while循環中並觀察它在按ENTER時的狀態。因此設置如果和裏面如果休息,這將爲你工作。 –

回答

0

閱讀整行的前貼好,自己解析它。如果該行爲空,則退出循環結束程序。如果不爲空,則將該行傳遞給新的掃描儀。

List<Integer> solutions = new LinkedList<>(); 

Scanner systemScanner = new Scanner(System.in); 
String line = null; 

while ((line = systemScanner.nextLine()) != null && !line.isEmpty()) { 
    Scanner lineScanner = new Scanner(line); 
    int p = lineScanner.nextInt(); 
    int c = lineScanner.nextInt(); 
    int d = p + c; 
    solutions.add(d); 
} 

Iterator<Integer> solution = solutions.iterator(); 
while (solution.hasNext()) { 
    int u = solution.next(); 
    System.out.println(u); 
} 
+0

非常感謝你! – limit2001