java - for 循环不迭代所有增量

标签 java loops file-io iteration java.util.scanner

我正在为大学的实验室任务编写一个程序,代码的作用相当明显,但是当它要求第一行,即循环中的第一个 1 时,您插入一个字符串并按回车键,它会自动直接跳转到循环中的最后一个增量(5)有什么想法吗?

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.util.Scanner;

public class limmerickWriter {
    public static void main(String[] args)throws Exception {

        Scanner limScan = new Scanner(System.in); //scanner to read user input

        System.out.println("please enter the name of the file");

        String fileName; 

        fileName = limScan.next(); //filename for the text file 

        PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(fileName))); //declaring a new file writer

        for (int i = 1; i <= 5; i++) //loop to get 5 seperate lines from the user
        {
            System.out.println("please enter line " + i );

            out.println(limScan.next()); //writes the contents of the scanner to the file

        }
        out.flush();
        out.close();
    }
}

最佳答案

使用 scanner.next() 读取时,空格将用作默认分隔符。这意味着,如果您的文件名插入了多个以空格分隔的单词,则将首先通过连续的 next() 调用来读取它们。

例如,在使用 scanner.next() 读取文件名时,如果插入:

测试 ATest BTest CTest DTest ETest

然后按Enter,您将看到在相关类路径中创建了一个名为test的文件,其中包含文本数据ATest BTest CTest DTest ETest.

尝试在 for 循环中使用 nextLine()

关于java - for 循环不迭代所有增量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20227934/

相关文章:

java - 插入到 `table` 不存在的地方

javascript - 在我的猜数游戏中遇到 while 循环问题

c# - loop is only looping Once 求解决办法 C#, MySQL

java - aws s3 java sdk 下载 pdf 损坏

python - 无法使用 MySQL 数据写入文件

c++ - 如何使用文件 I/O C++

java - 向 Log4j 2 事件添加属性

java - 如何使用 Java 调用 Rhino Javascript 解释器?

java - 二次贝塞尔曲线上的最近点

java - 遍历所有 SimpleTextBox