我有一个我无法看到的简单问题,希望另一组眼睛可以帮助我。除了我认为的文件阅读器之外,一切都很完美。我应该让用户输入将其放入文件,读取该文件并执行正确的操作。但由于某种原因,它只对用户输入的最后一个输入执行此操作,并且用户希望运行该程序的次数。
所以例如用户输入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();
}
答案 0 :(得分:4)
我想我发现了你的问题。就在这里:
else
bw2.write(input + ": " + word + " dollars and " + cents + " cents");
bw2.newLine();
当你真正写作input
时,你正在写input2
。
所以正确的代码是:
else
bw2.write(input2 + ": " + word + " dollars and " + cents + " cents");
bw2.newLine();
这说明了为什么你真的应该使用更具描述性而不是自相似的变量名称;它有助于防止愚蠢的小错误。 (例如,userInput
和fileInput
变量名称比input
和input2
更好。