扫描整数和for循环以扫描一些字符串

时间:2016-11-16 12:20:02

标签: java string integer java.util.scanner

我正在尝试扫描一个整数并运行一个循环来扫描字符串,直到该整数。但是这段代码会跳过第一个字符串......

import java.util.ArrayList;
import java.util.Scanner;

public class A1 {

    public static void main(String[] args) {
        ArrayList <String> A = new ArrayList<String>();
        Scanner sc = new Scanner(System.in);
        System.out.println("How many strings to add:");
        int a = sc.nextInt();
        for(int i=0; i<a; i++)
        {
            System.out.printf("Enter %dth string:\n", i+1);
            String s = sc.nextLine();
            A.add(s);
        }

        for(int i=0; i<A.size(); i++)
        {
            System.out.println(A.get(i));
        }
    }

}

任何解决方案?

1 个答案:

答案 0 :(得分:0)

只需将您的代码更改为以下内容:

import java.util.ArrayList;
import java.util.Scanner;

public class A1 {

    public static void main(String[] args) {
        ArrayList <String> A = new ArrayList<String>();
        Scanner sc = new Scanner(System.in);
        System.out.println("How many strings to add:");
        int a = sc.nextInt();
        for(int i=0; i<a; i++)
        {
            System.out.printf("Enter %dth string:\n", i+1);
            String s = sc.next();         //This will wait until you give argument
            A.add(s);
        }

        for(int i=0; i<A.size(); i++)
        {
            System.out.println(A.get(i));
        }
    }

}

浏览SO帖子 - Java Scanner doesn't wait for user input