我很难弄清楚为什么这不起作用。 Java只是没有执行while循环,文件显然没有下一行。
fileName = getFileName(keyboard);
file = new Scanner (new File (fileName));
pass = true;
String currentLine;
while (file.hasNextLine()) {
currentLine = file.nextLine();
System.out.println(reverse(currentLine));
}
这是我正在测试的文件。我得到它与前几段工作,但它似乎只是停止工作......:
Jabberwocky
'Twas brillig,以及狡猾的toves 火葬和gimble在wabe; 所有的模仿都是borogoves, 而且这个家庭咆哮着。
“小心Jabberwock,我的儿子! 咬伤的下颚,抓住的爪子! 小心Jubjub鸟,并避免 冷酷的Bandersnatch!“
他手里拿着他的蝎子剑: 很长一段时间他寻找的男人的敌人 所以他在Tumtum树上休息了, 并且想了一会儿。正如他所说的那样,他站着, Jabberwock,有着火焰的眼睛, 来到郁郁葱葱的木头, 当它来的时候又乱了!
一,二!一二!并通过 vorpal刀片变得嗤之以鼻! 他把它留下来了,头部已经死了 他回去了。
“你杀了Jabberwock? 来到我的怀里,我的男孩! O frabjous day! Callooh! Callay!” 他满心欢喜。
'Twas brillig,以及狡猾的toves 火葬和gimble在wabe; 所有的模仿都是borogoves, 而且这个家庭咆哮着。
- 穿过镜子,以及爱丽丝在那里找到的东西(1872年)。
/*
* Lab13a.java
*
* A program that prompts the user for an input file name and, if that file exists,
* displays each line of that file in reverse order.
* Used to practice simple File I/O and breaking code up into methods as well as a first
* step to implementing Lab13b.java - reversing the entire file and Lab13c.java writing
* output to a separate output file.
*
* @author Benjamin Meyer
*
*/
package osu.cse1223;
import java.io.*;
import java.util.*;
public class Lab13a {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
String fileName = "";
Scanner file;
boolean pass = false;
while (!pass) {
try {
fileName = getFileName(keyboard);
file = new Scanner (new File (fileName));
pass = true;
String currentLine;
while (file.hasNextLine()) {
currentLine = file.nextLine();
System.out.println(reverse(currentLine));
}
}
catch (FileNotFoundException e) {
System.out.println("There was a problem reading from " + fileName);
System.out.println("Goodbye.");
return;
}
}
}
// Given a Scanner as input prompts the user to enter a file name. If given an
// empty line, respond with an error message until the user enters a non-empty line.
// Return the string to the calling program. Note that this method should NOT try
// to determine whether the file name is an actual file - it should just get a
// valid string from the user.
private static String getFileName(Scanner inScanner) {
boolean pass = true;
String fileName = "";
while (pass) {
System.out.print("Enter an input name: ");
fileName = inScanner.nextLine();
if (fileName.length()!=0) {
pass = false;
}
else {
System.out.println("You cannot enter an empty string.");
}
}
return fileName;
}
// Given a String as input return the reverse of that String to the calling program.
private static String reverse(String inString) {
if (inString.length()==0) {
return "";
}
String reversed = "" + inString.charAt(inString.length()-1);
for (int x = inString.length()-2; x>=0; x--) {
reversed = reversed + inString.charAt(x);
}
return reversed;
}
}
答案 0 :(得分:0)
问题可能在于您的函数getFilename()或reverse()的实现。既然你已经声明你使用了一些段落我怀疑你的程序由于你的文件处理而失败了。它可能是您用来反转导致问题的文件中的字符串的逻辑。