标题:for (int i = 1; i <= x; i++)这个循环中为什么第一次不执行String s = sc. ...
取消只看楼主
niuzhenkang
Rank: 1
等 级:新手上路
帖 子:1
专家分:0
注 册:2018-3-14
结帖率:0
已结贴  问题点数:20 回复次数:0 
for (int i = 1; i <= x; i++)这个循环中为什么第一次不执行String s = sc.nextLine();
public class test2 {
    public static void main(String[] args) throws IOException {
        // 创建ArrayList集合对象
        ArrayList<String> array = new ArrayList<String>();
        // 创建集合元素
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入集合中元素个数");
        int x = sc.nextInt();
        for (int i = 1; i <= x; i++) {
            System.out.println("请输入集合中第" + i + "个元素");
            String s = sc.nextLine();
            // 添加到集合中
            array.add(s);
        }
        // 封装目的地
        BufferedWriter fw = new BufferedWriter(new FileWriter("test2.txt") );
        for (String s1 : array) {
            fw.write(s1+"\r\n");
        }
        // 关闭资源
        fw.close();
    }
运行结果:
请输入集合中元素个数
3
请输入集合中第1个元素
请输入集合中第2个元素
nihao
请输入集合中第3个元素
哈哈
搜索更多相关主题的帖子: int String 集合 元素 输入 
2018-03-14 10:19



参与讨论请移步原网站贴子:https://bbs.bccn.net/thread-485254-1-1.html




关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.197120 second(s), 8 queries.
Copyright©2004-2025, BCCN.NET, All Rights Reserved