In my quest to create a compact application, I'm working on a feature where a player can click a button to retrieve values from a file. The concept involves adding to an existing bank number if it already exists in the file. If not, a new bank number is created along with its respective amount:
package application;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintStream;
import java.util.Scanner;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.stage.Stage;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.TextField;
public class Main extends Application {
@Override
public void start(Stage primaryStage) {
try {
//BorderPane root = new BorderPane();
Parent root = FXMLLoader.load(getClass().getResource("Root.fxml"));
Scene scene = new Scene(root,400,400);
scene.getStylesheets().add(getClass().getResource("application.css").toExternalForm());
primaryStage.setScene(scene);
primaryStage.show();
} catch(Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
launch(args);
}
@FXML
private TextField banknumber;
@FXML
private TextField original;
@FXML
private TextField deposited;
@FXML
private TextField output;
@FXML
protected void onClick(ActionEvent event) throws FileNotFoundException{
PrintStream diskWriter = new PrintStream(new File("accounts.txt"));
Scanner diskReader = new Scanner(new File("accounts.txt"));
int origbal;
int addtobal = Integer.parseInt(deposited.getText());
String number = banknumber.getText();
if(diskReader.next().equals(number)){
origbal = diskReader.nextInt();
int newbal = origbal+addtobal;
diskWriter.println("Number: " + number + " Total: " + newbal);
}
else{
origbal = Integer.parseInt(original.getText());
int newbal = origbal+addtobal;
diskWriter.println("Number: " + number + " Total: " + newbal);
}
int newbal = origbal+addtobal;
output.setText("You have added $" + addtobal + " to bank number: " + number + "for a total of $" + newbal);
diskWriter.close();
}
}
An error has popped up during testing, and although the line numbers correspond with the paste bin, I can't figure out where things went wrong:
java.lang.RuntimeException: java.lang.reflect.InvocationTargetException
(...)
Caused by: java.lang.reflect.InvocationTargetException
(...)
Caused by: java.util.NoSuchElementException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
(...)