2016-09-30 203 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]); 
      } 
} 
}