for循环的第一次迭代自动继续扫描仪输入

时间:2014-08-25 03:09:59

标签: java printwriter

我有一个类从Scanner类获取输入并通过PrintWriter类输出。当程序到达for循环时,它会自动运行第一次迭代而无需等待用户输入。

应该读取插入项目1:

但是它会读取插入项目1插入项目2。

第一次迭代后一切正常。

对于为什么会发生这种情况有任何帮助将不胜感激。

InputSplicer(Scanner input)
{
    this.input = input;
    array = new ArrayList<String>();
}

void splice()
{
    System.out.println("What is the output file destination?");
    outputFile = input.next();
    outputFileFile = new File(outputFile);
    try {
        output = new PrintWriter(outputFileFile);
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    System.out.println("How many items are in the query?");
    lengthOf = input.nextInt();

    for(int i = 1; i <= lengthOf; i++)
    {   
        System.out.println("Insert item " + i);
        //spaces in output are not working for example item 1 cannot equal jason tavano can equal jasontavano

        s = input.nextLine();

        s.trim();

        if(s.equalsIgnoreCase("null"))
        {
            s = "";

        }
        if(i != lengthOf)
            array.add(s + pipe);
        else
            array.add(s);
    }   
    for(int i = 0; i < array.size(); i++)
        output.print(array.get(i));
    output.close(); 
}
}

3 个答案:

答案 0 :(得分:3)

Scanner.nextInt()不会读取其后的剩余换行符。稍后Scanner.nextLine()从流中读取字符,直到找到新的行字符。在使用Scanner.nextLine()后,您应该使用Scanner.nextInt()来开始阅读数字后面的行。

答案 1 :(得分:2)

<强>问题:

s = input.nextLine();

当您输入nextInt中的数字时,它会消耗它中的newLine字符,从而迭代到for循环中的第二个循环

<强>溶液

在进入循环之前首先使用newLine字符

<强>样品:

System.out.println("How many items are in the query?");
lengthOf = input.nextInt();
input.nextLine(); //will consume the newLine character from the input lengthOf 

答案 2 :(得分:1)

nextInt()方法不会从流中删除enter char,因此您应该在此之后清除该流以清除该行的剩余部分。

清除它的最简单方法是在开始循环之前调用nextLine()