In my code i have a try/catch statement where i am reading a file and defining the variable as an integer; however, when i try to edit the number and then write it back into the file, it can't see the variable. Find my code attached below
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 | import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo) import javax.swing.*; import java.io.*; import java.awt.Color; import java.awt.Font; import java.io.*; import java.util.ArrayList; import java.util.Scanner; import javax.swing.JFileChooser; import javax.swing.JOptionPane; import javax.swing.filechooser.FileNameExtensionFilter; /** * Write a description of class topup here. * * @author (your name) * @version (a version number or a date) */ public class topup extends Actor { /** * Act - do whatever the topup wants to do. This method is called whenever * the 'Act' or 'Run' button gets pressed in the environment. */ public void act() { try { String result1 = readFile( "Pointsr.txt" ); int points=Integer.parseInt(result1); // reading and creating an int variable } catch (Exception e){ e.printStackTrace(); } if (Greenfoot.mouseClicked( this )) { String passcode = JOptionPane.showInputDialog( "Enter your 4 integer code" ); int code=Integer.parseInt(passcode); //asks a person who has a code for topup to enter passcode if (code == 9876 ) { String topup = JOptionPane.showInputDialog( "Enter the number of credits you want to top up" ); //asking person who holds code for number of topup points int x=Integer.parseInt(topup); //changing string to int points = points + x; //adding the topup points checkPoints(); // checking if you're points will go above thirty so you don't breach the limit FileWriter fw = null ; //below writing file try { fw = new FileWriter( "Pointsr.txt" ); fw.write( "" +points); } catch (Exception e){ e.printStackTrace(); } finally { if (fw != null ) { try { fw.close(); } catch (Exception e) { e.printStackTrace(); } } } } } } public String readFile(String fileName) { InputStream istream = getClass().getResourceAsStream(fileName); Scanner in = new Scanner( new BufferedReader( new InputStreamReader(istream))); String text = "" ; while (in.hasNextLine()) { text += in.nextLine() + "\n" ; } return text; } public void checkPoints() { if (points > 30 ) { System.out.println ( "You can't top up, you have too many credits" ); Greenfoot.stop(); } } } |