简体   繁体   English

这是使用扫描仪扫描多个输入的方法

[英]Is this the way to scan multiple inputs using scanner

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();
        }
    }
}

there is nothing stored in input[0] . input[0]没有存储任何内容。 May I know why? 我可以知道为什么吗?

change your code to 将您的代码更改为

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

it needs to swallow up the linefeed 它需要吞下换行符

nextInt() wont consume the \\n (new line), then nextLine will consume \\n character from the number of lines ( left by nextInt ). nextInt()不会消耗\\ n(新行),然后nextLine将消耗行数中的\\ n字符(由nextInt保留)。 You can use Integer.parseInt(in1.nextLine()) or and another in1.nextLine() right after you nextInt(), to consume the \\n char. 您可以在nextInt()之后立即使用Integer.parseInt(in1.nextLine())或另一个in1.nextLine()来消耗\\ n字符。

Trace of your code 跟踪您的代码

    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();
    }

here is solution, just change input[i] = in1.nextLine(); 这是解决方案,只需更改input[i] = in1.nextLine(); to input[i] = in1.next(); input[i] = in1.next(); and it's working, i test it in my locally. 它正在工作,我在本地进行了测试。

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]);
            }
}
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM