java - FileReader 似乎不起作用

标签 java filereader

我有一个我看不到的简单问题,希望另一双眼睛可以帮助我解决。除了我认为的文件阅读器之外,一切都运行良好。我应该让用户输入将其放入文件中,读取该文件并执行正确的操作。但由于某种原因,它只对用户输入的最后一个输入执行此操作,并执行用户想要运行程序的次数。

例如,用户输入 3 次他想要运行提示符,他输入 344.34, 5533.23, 34.55,它正确地将其保存到文件中,但输出文件有

Thirty-four dollars and 55 cents
Thirty-four dollars and 55 cents
Thirty-four dollars and 55 cents

我不明白为什么要这样做。谢谢

   public class Driver 
   {
   public static void main(String[] args) throws IOException
   {    
    // reads from keyboard
    Scanner kb = new Scanner(System.in);
    //writes to file
    FileWriter fw =new FileWriter("input.txt");  
    BufferedWriter bw = new BufferedWriter(fw);

    double input; //variable to get users input

    System.out.println("How many times do you want to convert? ");
    int amount = kb.nextInt();
    //loop to go through users inputs and save to file
    do
    {
        System.out.println("Enter currency to change to words: ");  
        while(!kb.hasNextDouble())
        {
            System.out.println("Please enter a correct currency: ");
            kb.next();
        }

        input = kb.nextDouble();
        bw.write(String.valueOf(input));
        bw.newLine();
        amount--;

    }while(amount > 0 );
    bw.close();

    Scanner read = new Scanner(new FileReader("C:\\Users\\Karmen\\workspace\\currencytoword\\input.txt"));
    FileWriter fw2 =new FileWriter("output.txt");  
    BufferedWriter bw2 = new BufferedWriter(fw2);

    double input2;

    // loop to go through the file read and get convert the curreny to words and save in a output file.
    while(read.hasNext())
    {
        input2 = read.nextDouble();
        int dollar = (int) input2;
        int cents = (int)Math.round((input2 - dollar) * 100);
        String word = numToWord(dollar);
        if(word == "null")
        {
            bw2.write("Number too large");
        }
        else
            bw2.write(input + ": " + word + " dollars and " + cents + " cents");
            bw2.newLine();
    }
    System.out.println("Program is done");
    bw2.close();
}

最佳答案

我想我发现了你的问题。在这里:

else
        bw2.write(input + ": " + word + " dollars and " + cents + " cents");
        bw2.newLine();

当您真正应该编写input2时,您正在编写input。 所以正确的代码是:

else
        bw2.write(input2 + ": " + word + " dollars and " + cents + " cents");
        bw2.newLine();

这说明了为什么您确实应该使用更具描述性且不自相似的变量名称;它有助于防止愚蠢的小错误。 (例如,在这里,userInputfileInput 是比 inputinput2 更好的变量名称)

关于java - FileReader 似乎不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24621088/

相关文章:

javascript - 从本地硬盘读取 JSON 文件并解析为 React 应用程序

java - Java 中的字符与字符串?

java - 为什么@Qualifier 不允许在构造函数之上?

java - 仅具有公共(public)静态成员的公共(public)类

java - 由扫描仪引起的线程 "main"java.util.NoSuchElementException 中的异常

javascript - 使用纯 Javascript 在 Android 上使用 mosync/phonegap 从 SD 卡读取文件

java - 私有(private)模块和/或提供程序的简单使用

Javascript - 文件上传,readAsArrayBuffer?

objective-c - 使用 NSFileHandle 读取/写入文件的示例

java - 需要帮助逐行读取文件