Learning to navigate and input information into an application

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)
        (...)

Answer №1

The name of the file specified in your code is "accounts", not "accounts.txt". Additionally, there seems to be a missing definition for a button.

Upon correcting the file path

An issue arises with the Scanner on line 54, where it complains that next() is called despite there being no token left to scan. Typically, one would check if `hasNext()` returns true before proceeding.

Furthermore, attempting to read from a file that has not been fully written (i.e., close() has not been invoked) is discouraged.

Without knowing the intended purpose of your code, I am unable to provide specific recommendations for improvement.

Answer №2

If you're looking for a way to efficiently manage properties in Java, consider using the java.util.properties library. This library allows you to load properties from a file into a HashMap and access them easily.

For example, if your "accounts.txt" file looks like this:


banknumber1=origbal1
banknumber2=origbal2


    @FXML
    protected void handleOnClick(ActionEvent event) throws FileNotFoundException{
        Properties properties = new Properties();
        InputStream inputStream = new InputStream("accounts.txt");

        properties.load(inputStream);
        inputStream.close();

        String accountNumber = banknumber.getText();
        String originalBalance = properties.getProperty(accountNumber);
        int additionalBalance = Integer.parseInt(deposited.getText());

        if (originalBalance != null)
            properties.setProperty(accountNumber, Integer.parseInt(originalBalance) + additionalBalance);

        OutputStream outputStream = new OutputStream("accounts.txt");
        properties.store(outputStream);
        outputStream.close();
    }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Dynamically route a link from a React App to an Express server

Trying to connect a React JS app front end link to an Express server has been a challenge for me. Here's an Example: <a href="/pages">Pages</a> For the Express server, I included this code: app.get('/pages', (req, res) => ...

Mistake in transferring Konva. Collection via jQuery $.getJSON to Flask backend

I am looking to transmit the coordinates of all rectangles on a layer to my backend. I have been using var nodes = layer.find(".Rect"), which successfully prints the data (console.log(nodes)). However, when attempting to send this data using jQue ...

How do I determine whether an object is a Map Iterator using JavaScript?

I'm working on some NodeJS code that involves a Map Iterator object. How can I accurately determine if a Javascript object is a "Map Iterator"? Here are the methods I have attempted: typeof myMap.keys() returns 'Object' typeof myMap.keys() ...

Why isn't the selected value updating in ion-select Ionic 2 when using Angularjs 2?

Currently, I have the following code that is functioning well up to a certain point. However, I am encountering a small issue that I cannot seem to resolve. The problem lies in updating the ion-select after the user selects an option. Essentially, the UI d ...

Interactive quiz program based on object-oriented principles

As I work on developing a quiz app using JavaScript, everything seems to be going well. However, I've encountered an issue with validation where my code is validating the answers twice - once with the correct answer from the previous question and agai ...

Replace the checkbox display heading with a text box in the designated area

I'm new to using kendo ui Currently, I am attempting to show a text box in the first column header. Instead of the checkboxDisplay heading, I want to replace it with a text box. Could someone please provide guidance on how to resolve this issue? Here ...

Fragment Class Encountering Inflation Exception

I'm currently working on a project that involves using fragments. Every time I run a test on the project, I encounter an exception in my fragment class pointing to the inflater line of my onCreateView method, as shown below. Process: com.example.joey ...

Count of Impacted Rows in SQL Query

After exploring various topics related to my issue, I have not come across a satisfactory answer. Therefore, I have decided to share my problem here. The challenge at hand is as follows: I am working on a Java method that requires two parameters - restau ...

Is it feasible to execute a cross-site request forgery attack on a URL that delivers a JSON object as a response?

I am aware of the potential for a Cross-Site Forgery Attack that can target requests returning arrays by manipulating the Array constructor. For instance, let's say I have a site with a URL: foo.com/getJson that provides the following array: [&apos ...

Tips for stopping sitemesh from parsing HTML within a textarea

Incorporating Sitemesh for page decoration in my web application has been a great addition. One issue that I have encountered involves a form where the textarea field contains an entire HTML page. The challenge arises when Sitemesh parses this page and i ...

Tips for adapting this code to be compatible with react-router v6

Within ProtectedRoute.js, the following code is implemented: const ProtectedRoute = ({ component: Component, ...rest }) => { const { loading, isAuthenticated, user } = useSelector((state) => state.user); return ( <Fragment> {!load ...

Sending a two-dimensional array through an HTML form field using JavaScript

Prior to reading: Please note that if you are only interested in answering the question, you can skip ahead to "The Question" at the end of this post. My current project involves developing a feature for a website that enables users to upload and share pr ...

Change the input value by clicking different buttons

Looking for a way to change the value or source of an input when clicking on different buttons? For example, clicking on Button 1 changes the input to "apple" and Button 2 changes it to "orange", etc. Here is a snippet of what I have tried so far: $(doc ...

What is the advantage of using a linked list in Selenium webdriver for collecting links or dropdown contents that have multiple matches?

For instance, a sample code I encountered during a recent interview is as follows: List linkItems = driver.findElements(By.tagName("a")); ...

The HTML5 camera feature remains active even after navigating to a different page in an AngularJS application

I am currently exploring the video capabilities of HTML5. Using a directive userMedia, I have successfully activated my camera on my MacBook through navigator.getUserMedia() (using an adapter for cross-browser compatibility with supported browsers). Howev ...

Guide on saving the token in local storage or cookies to grant access to specific web pages for users

Currently, I am in the process of developing an authentication system using Node.js, MySQL, and Express. Initially, I focused on saving and verifying user credentials in the database. Recently, I incorporated JWT (JSON Web Token) into the system. My next s ...

Retrieving JSON data in JavaScript from PHP

My current challenge involves retrieving PHP data from my JavaScript code and displaying it in the dayta div id. Instead of getting the desired result (which is the firstname in my JSON file), I am encountering an issue where I receive undefined. This has ...

Received a null pointer exception when attempting to call a method from one class within another

Currently, I am working on automating the Facebook login and logout processes, but I have encountered some issues. Essentially, I have developed a FacebookLogOutTest class that needs to execute FacebookLogIn first before proceeding. Below are the classes: ...

How can you specify the maximum width and height for a TextField in JavaFX using CSS?

Is there a way to set preferred and maximum width and height for a TextField using CSS? ...

The addClass() method in jQuery does not seem to be working as it fails to add the

The code is functioning properly, generating all the necessary elements as expected. However, I am encountering an issue with the jquery addClass method not applying the class. As a beginner in utilizing jquery methods within a javascript function, any g ...