Narasima.Codes
Narasima.Codes

Reputation: 79

NumberFormatException error in my code.I made sure that every file aren't empty

I am creating a daily saving log. While creating I got this NumberFormatException.I need some help to complete the project.

here's the code I'm working on.

package app;

import java.awt.EventQueue;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Scanner;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.SwingConstants;
import java.awt.Font;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.Color;
import javax.swing.JSeparator;
import javax.swing.border.MatteBorder;

public class Application {
    
     BufferedWriter log = null;
     BufferedWriter bal = null;

    private JFrame frame;

    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    Appilcation window = new Appilcation();
                    window.frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the application.
     */
    public Appilcation() {
        try {
            initialize();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    /**
     * Initialize the contents of the frame.
     * @throws IOException 
     */
    @SuppressWarnings("resource")
    private void initialize() throws IOException,NumberFormatException{
        frame = new JFrame();
        frame.setUndecorated(true);
        frame.setBounds(100, 100, 450, 420);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().setLayout(null);

         
            log= new BufferedWriter(new FileWriter(new File("Log.txt")));//writer for log
            bal= new BufferedWriter(new FileWriter(new File("bal.txt")));// "      "  bal
            Scanner File = new Scanner(new File("bal.txt"));
           //SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");  
          // Date date = new Date(); 
           
           
        
        JPanel panel = new JPanel();
        panel.setBackground(new Color(255, 0, 102));
        panel.setBounds(0, 0, 450, 420);
        frame.getContentPane().add(panel);
        panel.setLayout(null);
        
        JLabel lblDdmmyyyy = new JLabel("dd/mm/yyyy");
        lblDdmmyyyy.setFont(new Font("ARCADE", Font.PLAIN, 16));
        lblDdmmyyyy.setHorizontalAlignment(SwingConstants.CENTER);
        lblDdmmyyyy.setHorizontalTextPosition(SwingConstants.CENTER);
        lblDdmmyyyy.setBounds(10, 11, 100, 29);
        panel.add(lblDdmmyyyy);
        
        JLabel lblHh = new JLabel("hh:mm:ss");
        lblHh.setFont(new Font("ARCADE", Font.PLAIN, 16));
        lblHh.setHorizontalAlignment(SwingConstants.CENTER);
        lblHh.setBounds(324, 11, 100, 29);
        panel.add(lblHh);
        
        JButton btnAddSavings = new JButton("Add");
        btnAddSavings.setBackground(new Color(255, 255, 0));
        btnAddSavings.setFont(new Font("ARCADE", Font.PLAIN, 16));
        btnAddSavings.addActionListener(new ActionListener() {
            //something is not ryt here
            public void actionPerformed(ActionEvent arg0) {
                String Add=JOptionPane.showInputDialog(panel,"Enter Amount to be added");
                String s=/*sdf.format(date)+**/"   "+Add+"(Added)";
                String Bal="";
                while(File.hasNextLine())
                     Bal=File.nextLine(); 
                int aa=Integer.parseInt(Bal);
                int bb =Integer.parseInt(Add);
                int sum=aa+bb;
                
                    try {
                        bal.write(sum+"\n");
                        log.write(s+"\n");
                        
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
              
               
               
               
            }
        });
        btnAddSavings.setBounds(138, 150, 173, 64);
        panel.add(btnAddSavings);
        
        JButton btnRemove = new JButton("Remove");
        btnRemove.setBackground(new Color(255, 127, 80));
        btnRemove.setFont(new Font("ARCADE", Font.PLAIN, 16));
        btnRemove.setBounds(138, 225, 173, 64);
        panel.add(btnRemove);
        
        JButton btnIdeas = new JButton("ideas");
        btnIdeas.setBackground(new Color(153, 204, 255));
        btnIdeas.setFont(new Font("ARCADE", Font.PLAIN, 16));
        btnIdeas.setBounds(138, 300, 173, 34);
        panel.add(btnIdeas);
        
        JButton btnExit = new JButton("Log");
        btnExit.setBackground(new Color(204, 204, 255));
        btnExit.setBounds(138, 345, 71, 23);
        panel.add(btnExit);
        
        JButton btnExit_1 = new JButton("Exit");
        btnExit_1.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {
                System.exit(0);
            }
        });
        btnExit_1.setBackground(new Color(204, 204, 255));
        btnExit_1.setBounds(240, 345, 71, 23);
        panel.add(btnExit_1);
        
        JLabel lblRs = new JLabel("0   Rs.");
        lblRs.setBackground(new Color(0,0,0,0));
        lblRs.setFont(new Font("Bebas", Font.PLAIN, 23));
        lblRs.setHorizontalAlignment(SwingConstants.CENTER);
        lblRs.setBounds(105, 81, 239, 58);
        panel.add(lblRs);
        
        JPanel panel_1 = new JPanel();
        panel_1.setBorder(new MatteBorder(2, 2, 2, 2, (Color) new Color(0, 0, 0)));
        panel_1.setBackground(new Color(0,0,0,0));
        panel_1.setBounds(105, 81, 239, 58);
        panel.add(panel_1);
        bal.close();
        log.close();
        
    }
    }

and the error message :

Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: For input string: "" at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:68) at java.base/java.lang.Integer.parseInt(Integer.java:668) at java.base/java.lang.Integer.parseInt(Integer.java:776) at app.Appilcation$2.actionPerformed(Appilcation.java:113) at java.desktop/javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1967) at java.desktop/javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2308) at java.desktop/javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:405) at java.desktop/javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:262) at java.desktop/javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:279) at java.desktop/java.awt.Component.processMouseEvent(Component.java:6632) at java.desktop/javax.swing.JComponent.processMouseEvent(JComponent.java:3342) at java.desktop/java.awt.Component.processEvent(Component.java:6397) at java.desktop/java.awt.Container.processEvent(Container.java:2263) at java.desktop/java.awt.Component.dispatchEventImpl(Component.java:5008) at java.desktop/java.awt.Container.dispatchEventImpl(Container.java:2321) at java.desktop/java.awt.Component.dispatchEvent(Component.java:4840) at java.desktop/java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4918) at java.desktop/java.awt.LightweightDispatcher.processMouseEvent(Container.java:4547) at java.desktop/java.awt.LightweightDispatcher.dispatchEvent(Container.java:4488) at java.desktop/java.awt.Container.dispatchEventImpl(Container.java:2307) at java.desktop/java.awt.Window.dispatchEventImpl(Window.java:2762) at java.desktop/java.awt.Component.dispatchEvent(Component.java:4840) at java.desktop/java.awt.EventQueue.dispatchEventImpl(EventQueue.java:772) at java.desktop/java.awt.EventQueue$4.run(EventQueue.java:721) at java.desktop/java.awt.EventQueue$4.run(EventQueue.java:715) at java.base/java.security.AccessController.doPrivileged(AccessController.java:389) at java.base/java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:85) at java.base/java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:95) at java.desktop/java.awt.EventQueue$5.run(EventQueue.java:745) at java.desktop/java.awt.EventQueue$5.run(EventQueue.java:743) at java.base/java.security.AccessController.doPrivileged(AccessController.java:389) at java.base/java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:85) at java.desktop/java.awt.EventQueue.dispatchEvent(EventQueue.java:742) at java.desktop/java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:203) at java.desktop/java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:124) at java.desktop/java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:113) at java.desktop/java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:109) at java.desktop/java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101) at java.desktop/java.awt.EventDispatchThread.run(EventDispatchThread.java:90)

things I tried:

-> made sure all the files are not empty.

little help here plss.

Upvotes: 0

Views: 364

Answers (2)

Nowhere Man
Nowhere Man

Reputation: 19565

There are several problems in the following snippet related to the non-validated inputs

  1. Add may be empty or not a number when returned from the JOptionPane
  2. Bal may be empty: actually Bal is assigned the last line from the file. So, file may be non-empty, but it may contain a trailing empty line and thus Bal is "";
    String Add=JOptionPane.showInputDialog(panel,"Enter Amount to be added");
    String s=/*sdf.format(date)+**/"   "+Add+"(Added)";
    String Bal="";
    while(File.hasNextLine())
        Bal=File.nextLine(); 
    int aa=Integer.parseInt(Bal);
    int bb =Integer.parseInt(Add);
    int sum=aa+bb;

So you may want to implement a separate method to parse numbers without fail:

    private static int getNumber(String s) {
        int res = 0;
        try {
            res = Integer.parseInt(s);
        } catch (Exception ex) {
            System.err.println("Failed to parse number from '" + s + "', " + ex.getMessage());
            res = 0;
        }
        return res;
    }
// ...
    int aa = getNumber(Bal);
    System.out.printf("DEBUG: Bal='%s' -> aa=%d%n", Bal, aa);
    int bb = getNumber(Add);
    System.out.printf("DEBUG: Add='%s' -> bb=%d%n", Add, bb);

Upvotes: 0

Valerij Dobler
Valerij Dobler

Reputation: 2794

The problem seems to be that one file has an empty line. Before parsing Bal, Check if it's empty.

Upvotes: 0

Related Questions