2011-03-24 4 views
0

내 프로그램에 어떤 문제가 있는지 물어보고 싶습니다. 내 프로그램은 스택에 관한 것이지만 오류는 없습니다.하지만 제 문제는 스택의 모든 작업을 처리해야한다는 것입니다. 프로그램을 닫더라도, 다음 번에 열면 이전 데이터가 계속 표시됩니다. 필자와 파일 판독기를 사용했지만 닫을 때마다 다시 열면 이전 데이터가 나타나지 않습니다. 조언이 있으십니까? 당신이 프로그램 버퍼 출력은 디스크로 플러시됩니다 그런 식으로 종료하기 전에 FileWriter.close를 호출해야합니다 saveMe()왜 읽지 않을까요?

를 호출하기 전에 System.exit를 호출하기 때문에 덕분에 .. 여기

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); 

    } 
} 
+1

'it'에 오류가 오히려 강한 문이 없다 : –

답변

0

.. 내 프로그램입니다.

+0

I

Scanner txtFile = new Scanner(File source); 

체크 아웃 그것이 문제라고 생각하지 마십시오. System.exit()는 액션 이벤트 소스가 exit 버튼에서 나왔을 때만 호출됩니다. –

1

실제로 많은 문제가 있습니다.

알렉산더의 답변에 대해서는 푸시/팝 전화가 올 때마다 저장되므로 saveMe()이 호출되고 있습니다.

saveMe()에 있지만 스택의 첫 번째 요소 앞에 :을 쓰면 다시 읽어 들여 여분의 빈 요소가 제공됩니다. :을 쓰기 전에 x! = 0인지 확인하십시오. 프로그램을 시작하면, ID가 길이가 0이됩니다

  1. :

    그리고 readMe(), 당신은 두 가지 방법으로 잘못 id.length에 대한 nextLine()를 호출

    . for 루프의 끝 조건으로 x<id.length을 사용하면 안됩니다 (어쨌든 x가 잘못되었으므로 컨텍스트에서 y 여야합니다). txtFile.hasNext()을 사용하여 읽을 스택 요소가 더 있는지 확인하십시오.
  2. 파일에 스택이 하나만 있고 여러 개가 아닙니다. 스캐너의 구분 기호를 :으로 설정하고 textFile.useDelimiter(":")으로 설정 한 다음 next()을 호출하면됩니다. saveMe()을 수정하지 않으면 시작 부분에 빈 칸 하나가 추가됩니다.

또한 Nicklamort의 대답에 따라 new Scanner(new File("Sample.txt"))으로 전화하여 실제 파일을 열어야합니다.

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

난 당신이 구문 분석하려고 생각 : 새로운 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(); 
} 
+0

당신의 답을 +1했습니다 : P – darvids0n

1

당신이 파일에서 읽으려고하는 새로운 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++; 
    } 

} 

예의

예 리터럴 문자열 : "Sample.TXT "

당신은 스캐너 생성자에 실제 파일 개체를 전달하려면 다음 docs

관련 문제