我正在为大学的实验室任务编写一个程序,代码的作用相当明显,但是当它要求第一行,即循环中的第一个 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/