我正在尝试将数字0写入名为amountSessions的文件,这是第一次创建时,您可以在注释“On the first run”下面的if语句中查看到目前为止,但稍后在程序中(在writeToFile方法的末尾)注释“每次运行的增量数”下面我希望每次程序运行时将我前面讨论过的0增加1。不幸的是,当我编译并运行程序时,我得到以下错误。为什么是这样?非常感谢大家!
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:862)
at java.util.Scanner.next(Scanner.java:1485)
at java.util.Scanner.nextInt(Scanner.java:2117)
at java.util.Scanner.nextInt(Scanner.java:2076)
at math_program.fileWriting.getInt(fileWriting.java:62)
at math_program.fileWriting.writeToFile(fileWriting.java:41)
//Test
package testing;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
import javax.swing.JOptionPane;
public class Kappa
{
String numberFilePath = "/Users/john/Desktop/numProblems.txt";
String sessionFilePath = "/Users/john/Desktop/amountSessions.txt";
File testFile = new File(numberFilePath);
File amountSessions = new File(sessionFilePath);
public void writeToFile() throws IOException
{
//On the first run
if(!testFile.exists())
{
testFile.createNewFile();
} else if(!amountSessions.exists())
{
amountSessions.createNewFile();
FileWriter sessionWriter = new FileWriter(amountSessions);
sessionWriter.write("0");
sessionWriter.close();
}
FileWriter durationWriter = new FileWriter(testFile);
FileWriter sessionWriter = new FileWriter(amountSessions);
//Write Duration
String ans = prompt();
durationWriter.write(ans);
durationWriter.close();
//Increment number each run
sessionWriter.write(getInt());
sessionWriter.close();
System.exit(0);
}
public void grab() throws FileNotFoundException
{
Scanner numProblemsReader = new Scanner(new File("/Users/john/Desktop/numProblems.txt"));
Scanner numSessionReader = new Scanner(new File("/Users/john/Desktop/amountSessions.txt"));
int number = numProblemsReader.nextInt();
int numSessions = (numSessionReader.nextInt() + 1);
System.out.println("The number read from the file is: " + number);
File replaceFile = new File("/Users/john/Desktop/session" + numSessions + ".txt");
testFile.renameTo(replaceFile);
}
public String getInt() throws FileNotFoundException
{
Scanner numSessionReader = new Scanner(new File("/Users/john/Desktop/amountSessions.txt"));
int numSessions = ((numSessionReader.nextInt()) + 1);
String newNum = Integer.toString(numSessions);
return newNum;
}
public String prompt()
{
String ans = JOptionPane.showInputDialog ("Enter the new amount of problems per training session (with number in minutes):");
while(!ans.matches("[0-9]+"))
{
ans = JOptionPane.showInputDialog ("Please re-enter the new amount of problems per training session (with number in minutes):" );
}
return ans;
}
}
答案 0 :(得分:0)
更改
} else if(!amountSessions.exists())
要
}
if(!amountSessions.exists())
否则,只有第一个文件不存在才会被创建。