0 java iteration file-io loops java.util.scanner
我正在为uni编写一个实验室任务的程序,代码将使得相当明显的是什么,但是当它要求第一行时,即循环中的第一个1,并且插入一个字符串并按Enter键,它会自动直接跳到循环中的最后一个增量(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();
}
}
Run Code Online (Sandbox Code Playgroud)
使用scanner.next()空格进行读取时,将其用作默认分隔符.这意味着如果您的文件名插入了多个以空格分隔的单词,则将首先使用连续next()调用来读取它们.
例如,在阅读filename使用时scanner.next(),如果插入:
test ATest BTest CTest DTest ETest
然后点击Enter,您将看到test在相关的类路径中创建了一个带有名称的文件,其中包含文本数据ATest BTest CTest DTest ETest.
尝试nextLine()在for循环中使用.
| 归档时间: |
|
| 查看次数: |
102 次 |
| 最近记录: |