2016-09-30 202 views
0
import java.util.Scanner; 
public class servlt { 
    public static void main (String args[]){ 
     Scanner in1 = new Scanner(System.in); 
     int t = in1.nextInt(); 
     int n=0, m=0; 
     String input[] = new String[t]; 
     for (int i = 0; i<t; i++){ 
      input[i] = in1.nextLine(); 
     } 
    } 
} 

input[0]中沒有任何存儲。我可以知道爲什麼嗎?這是使用掃描儀掃描多個輸入的方式

+1

你能定義「多輸入」嗎? – TheLostMind

+0

輸入可以以任意數量的行給出。第一個輸入顯示接下來會有多少個輸入,所以如果我給3作爲第一個輸入,這意味着我將再給出3個輸入 – Mahesh

+0

然後使用'nextLine'讀取數據並使用'\\ s +'分割。第一個令牌將是輸入值的數量,下面的令牌將是實際的輸入值。 – TheLostMind

回答

2

改變你的代碼

int t = in1.nextInt(); 
in1.nextLine(); 

它需要吞掉換行

+0

這就是我一直這麼做的......簡單。 – DevilsHnd

0

nextInt()不會消耗\ n(新行),然後nextLine將消耗\ n字符的數量行(由nextInt左邊)。您可以在nextInt()之後立即使用Integer.parseInt(in1.nextLine())或另一個in1.nextLine()來消耗\ n字符。

跟蹤代碼的

Scanner in1 = new Scanner(System.in); 
    int t = in1.nextInt(); // read a number (let say 3) 
    int n=0, m=0; 
    String input[] = new String[t]; 
    for (int i = 0; i<t; i++){ 
     input[i] = in1.nextLine(); // the first time nextLine will read the \n char 
    // The second time an 1 (for example) 
    // And the third time a 2 (for example)\ 
    } 

    // Finally you will have an array like this 
    // input[0] = "\n" 
    // input[0] = "1" 
    // input[0] = "2" 

FIX

Scanner in1 = new Scanner(System.in); 
    int t = Integer.parseInt(in1.nextLine()); 

    int n=0, m=0; 
    String input[] = new String[t]; 
    for (int i = 0; i<t; i++){ 
     input[i] = in1.nextLine(); 
    } 
0

這裏的解決方案,只是改變input[i] = in1.nextLine();input[i] = in1.next();,它的工作,我測試它在我的本地。

import java.util.Scanner; 

public class servlt { 

     public static void main (String args[]){ 
      Scanner in1 = new Scanner(System.in); 
      System.out.println("enter total number you want to store:: "); 
      int t = in1.nextInt(); 
      int n=0, m=0; 
      String input[] = new String[t]; 
      for (int i = 0; i<t; i++){ 
       System.out.println("enter "+i+"th number :"); 
       input[i] = in1.next(); 
      } 
      for (int j=0;j<t;j++) 
      { 
       System.out.println("input["+j+"] value is : "+input[j]); 
      } 
} 
}