gpt4 book ai didi

java - FileReader 似乎不起作用

转载 作者:行者123 更新时间:2023-12-01 18:30:05 26 4
gpt4 key购买 nike

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

例如,用户输入 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com