简体   繁体   中英

why won't it read?

I want to ask what's the problem with my program.. My program is about stacks, there's no error in it, but my problem is, our requirement is do all operations in stacks and then, even if you close the program, the next time you will open it, the previous data should still be displayed.. I used the filewriter and filereader, but every time I close it, then open it again, the previous data doesn't appear.. Any advice? thanks.. here's my program..

import java.util.*;
import java.awt.*;
import java.io.*;
import javax.swing.*;
import java.awt.event.*;
public class STACKS extends JFrame implements ActionListener
{
    private JButton push,pop,peek,display,exit;
    private JLabel Stack;
    static int arr[],x=0,b=0,xy=0,c=0;
    static String in="",INDEX="",d="",s="";
    static String id[]={};

    public STACKS()
    {
        super("STACKS MENU!^_^");
        Container c=getContentPane();
        c.setLayout(new FlowLayout());
        Stack=new JLabel("STACKS MENU!^_^");    c.add(Stack);
        push=new JButton("Push!^-^");
        pop=new JButton("Pop!^-^");
        peek=new JButton("Peek!^-^");
        display=new JButton("Display!^-^");
        exit=new JButton("Exit!^-^");
        push.addActionListener(this);           c.add(push);
        pop.addActionListener(this);            c.add(pop);
        peek.addActionListener(this);           c.add(peek);
        display.addActionListener(this);        c.add(display);
        exit.addActionListener(this);           c.add(exit);
        setVisible(true);
        setSize(150,250);
    }
    public static void saveMe() throws IOException
    {
        File data1=new File("Sample.txt");      //a file was created...
        PrintWriter out=new PrintWriter(new BufferedWriter(new FileWriter(data1,true)));
        for(int x=0;x<4;x++)
        {
            out.write(":"+arr[x]);  xy=1;           //here in this section, I put : in every elements inside the array..
        }
        out.close();

    }
    public static void readMe() throws IOException
    {
        Scanner txtFile=(new Scanner("Sample.txt"));

        for(int y=0;x<id.length;y++)
        {
            s=txtFile.nextLine();
            id=s.split(":");
            arr[y]=Integer.parseInt(id[y]);
        }

    }
    public  void actionPerformed(ActionEvent a)
    {
        try
        {
            readMe();                               //here is where the previous data will be read..
        }
        catch(Exception e)
        {
            JOptionPane.showMessageDialog(null,"File not found! readme !^,^");
        }
        if (xy==0)
        {
            INDEX=JOptionPane.showInputDialog(null,"Enter LENGTH of the array!");
            c=Integer.parseInt(INDEX); xy=1;
            arr=new int[c];
        }
        if(a.getSource()==push)
        {
            in=JOptionPane.showInputDialog(null,"Enter integer to be pushed!");
            b=Integer.parseInt(in);
            arr[x]=b;   x+=1;
            if(x==c)
            {
                JOptionPane.showMessageDialog(null,"WARNING! The stacks are full, please pop something!^-^");
            }
            if(x>c)
            {
                JOptionPane.showMessageDialog(null,"Sorry, the stacks are full,please pop something first!^-^");
                x-=1;
            }
        }
        else if(a.getSource()==pop)
        {

            arr[x-1]=0;x-=1;
            JOptionPane.showMessageDialog(null,"The value has been popped!^-^");
            if(x==0)
            {
                JOptionPane.showMessageDialog(null,"The stacks are empty, push something!^-^");
            }

        }
        else if(a.getSource()==peek)
        {
            JOptionPane.showMessageDialog(null,"The value is "+arr[x-1]+"! ^-^");
        }
        else if(a.getSource()==display)
        {
            for(int y=c-1;y>-1;y--)
            {
                d+="*** "+arr[y]+" ***\n";
            }
            JOptionPane.showMessageDialog(null,"The value inside the stacks are:\n"+d);
            d="";
        }
        else if(a.getSource()==exit)
        {
            System.exit(0);
        }
            try
        {
            saveMe();                   //here is where the file will be saved..
        }
        catch(Exception e)
        {
            JOptionPane.showMessageDialog(null,"File not found!^,^");
        }
    }
    public static void main(String args[])
    {
        STACKS pot=new STACKS();
        pot.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    }
}

There's a number of issues here actually.

In terms of Alexander's answer, you do save after every push/pop call, so saveMe() is being called.

In saveMe() , though, you write : before the first element of the stack, so reading it back in will always give an extra blank element. Check whether x != 0 before writing a : .

And in readMe() , you are calling nextLine() for id.length, which is incorrect in two ways:

  1. When you start the program, id will have length zero. You should not use x<id.length as the end condition of the for loop (x is wrong anyway, it should have been y in your context). Use txtFile.hasNext() to check if there are any more stack elements to read.
  2. Your file contains the stack entirely on one line, not multiple. What you should be doing is setting the delimiter of the Scanner to : with textFile.useDelimiter(":") , and then calling next() . Also remember that unless you correct saveMe() there will be one extra element at the beginning which is blank.

Also in readMe() , as per Nicklamort's answer, you need to call new Scanner(new File("Sample.txt")) to open the actual file.

Example of a new readMe()

public static void readMe() throws IOException
{
    Scanner txtFile=(new Scanner(new File("Sample.txt")));
    int y = 0;
    txtFile.useDelimiter(":");
    while(txtFile.hasNext())
    {
        arr[y]=txtFile.nextInt();
        y++;
    }

}

Example of a new saveMe()

public static void saveMe() throws IOException
{
    File data1=new File("Sample.txt");      //a file was created...
    PrintWriter out=new PrintWriter(new BufferedWriter(new FileWriter(data1,false))); // don't append, overwrite existing data since we are saving the entire stack each time
    for(int x=0;x<arr.length;x++)
    {
        if(x != 0) { out.write(":"); }           //here in this section, I put : in every elements inside the array..
        out.write(arr[x]);  xy=1;
    }
    out.flush(); // force writing to disk
    out.close();
}

When you try to read from file:

Scanner txtFile=(new Scanner("Sample.txt"));

I think you are trying to parse the literal string: "Sample.txt"

You want to pass the actual file object to the Scanner constructor:

Scanner txtFile = new Scanner(File source);

Check out the docs

Because you call System.exit before calling saveMe()

You MUST call FileWriter.close before you terminate the program, that way the buffer output will be flushed to disk.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM