【问题标题】:for loop not iterating through all incrementsfor 循环没有遍历所有增量
【发布时间】:2013-11-26 21:04:55
【问题描述】:

我正在为 uni 的一个实验室任务编写一个程序,代码的作用相当明显,但是当它要求第一行时,即循环中的第一行,你插入一个字符串,然后点击回车,它会自动跳转到循环中的最后一个增量(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();
    }
}

【问题讨论】:

  • 你试过调试吗?代码对我来说看起来不错。
  • 我使用的是 Eclipse IDE,所以它会在编译前自动调试
  • 不,它没有。 “调试”是指在调试器中运行您的代码,或将调试器附加到您的应用程序。
  • 虽然这个问题现在可能已经回答了,但是你应该知道,调试并不意味着报告编译错误,而是通过使用调试器逐步执行一个应用程序(尝试点击左侧的在文本编辑器中 eclipse 并使用“bug”符号运行应用程序;))

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


【解决方案1】:

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

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

test ATest BTest CTest DTest ETest

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

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

【讨论】:

    猜你喜欢
    • 2017-02-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-23
    • 2015-07-24
    • 2015-12-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多