【发布时间】:2016-06-08 21:40:43
【问题描述】:
我的 Java 编程入门课程有一个编程作业,但遇到了几个小问题。这是作业:
我要编写一个程序,它接受来自用户的两个输入:一个是 .txt 文件的名称,第二个输入是 long 类型的整数。它将使用用户输入的文件名创建一个新的 File 对象,然后通过将 File 对象传递给 PrintWriter 构造函数来获取一个 PrintWriter 对象。如果找到该文件,它将读取整数。
然后它将使用递归的方法将用户输入的数字反转(例如,如果用户输入一个数字 123456,它会将数字反转为 654321)。然后它会将反转的数字写入 .txt 文件和屏幕。
这是我的代码:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.io.PrintWriter;
public class Prog2c
{
public static void main(String[] args)
{
File inputFile = null; // File object for user's file
Scanner fileReader = null; // reads user's file
PrintWriter fileWriter = null; // writes to user's file
Scanner scan = new Scanner(System.in);
String fileName = null;
long number = 0;
try
{
fileName = scan.nextLine();
number = scan.nextLong(); // reads the whole number from the user
inputFile = new File(fileName); // creates new File object with user's file
fileReader = new Scanner(inputFile); // reads contents of user's file
System.out.println("Program 2, Christopher Moussa, masc1754");
if (inputFile.exists())
{
System.out.println("The file " + fileName + " is ready for writing."); // throws FileNotFoundException if
fileWriter = new PrintWriter(inputFile);
number = reverseNumber(number);
fileWriter.println(number); // performs recursive method on number inputted by user
System.out.println("File " + inputFile + " exists? " + inputFile.exists()); // checks to see if file exists
while (fileReader.hasNextLong())
{
number = fileReader.nextLong();
System.out.println(number); // prints contents of the file
}
}
}
catch (FileNotFoundException exception) // in case the file is not found or does not exist
{
System.out.println("FileNotFoundException file was not found: " + exception.getMessage());
System.exit(0);
}
finally
{
if (null != fileReader)
{
scan.close(); // closes scanner
fileWriter.close();
}
}
}
public static long reverseNumber(long number) // Recursive Method
{
if (number < 10) // Base Case 1: In case the number
{ // is a single digit number, I will
System.out.println(number); // just return the number
return number;
}
else // Recursion: This will take the
{ // remainder of the original number
System.out.print(number % 10); // and print it. It will then divide
reverseNumber(number/10); // the number by 10 to truncate it by
return number; // one digit. It will then return the value.
}
}
}
这是我的问题:
当我运行程序时,写入.txt文件的数字是我输入的原始数字,而不是反转的数字(反转的数字是应该写入.txt文件的数字)。即使我有一个扫描仪应该读取文件的内容并将数字打印到屏幕上(这是我的程序中的 while 语句,对吗?)。我关于为什么 PrintWriter 没有将反转的数字写入 .txt 文件的想法是因为您不能将方法的结果分配给变量?我不完全确定。任何关于如何将反转的数字写入 .txt 文件,然后将该 .txt 文件的内容(只有反转的数字)打印到屏幕上的建议/建议将不胜感激,谢谢。
【问题讨论】:
-
您没有颠倒号码。您只是递归地将其分解为单个数字并打印出来。函数返回后,您不会得到相反的数字,而是返回与开始时相同的数字
标签: java file-io fileoutputstream