How to fix bug with endless writing of numbers using FileWriter with append argumentHow to round a number to n decimal places in JavaHow do I write a correct micro-benchmark in Java?Java FileWriter with append modeHow to append text to an existing file in JavaHow do I create a file and write to it in Java?How do I fix android.os.NetworkOnMainThreadException?How to fix java.lang.UnsupportedClassVersionError: Unsupported major.minor versionDrawing an image in JScrollPane within scaleWorking on a java based chatting application using threadingCan't write number with FileWriter

Why Is Death Allowed In the Matrix?

Can I ask the recruiters in my resume to put the reason why I am rejected?

What is the word for reserving something for yourself before others do?

How did the USSR manage to innovate in an environment characterized by government censorship and high bureaucracy?

How to format long polynomial?

Fencing style for blades that can attack from a distance

How do we improve the relationship with a client software team that performs poorly and is becoming less collaborative?

Mathematical cryptic clues

Have astronauts in space suits ever taken selfies? If so, how?

Email Account under attack (really) - anything I can do?

How can I prevent hyper evolved versions of regular creatures from wiping out their cousins?

Python: next in for loop

Prove that NP is closed under karp reduction?

What do you call a Matrix-like slowdown and camera movement effect?

How to write a macro that is braces sensitive?

In Japanese, what’s the difference between “Tonari ni” (となりに) and “Tsugi” (つぎ)? When would you use one over the other?

What defenses are there against being summoned by the Gate spell?

How to say job offer in Mandarin/Cantonese?

Font hinting is lost in Chrome-like browsers (for some languages )

How can I make my BBEG immortal short of making them a Lich or Vampire?

What are the differences between the usage of 'it' and 'they'?

What does it mean to describe someone as a butt steak?

The Two and the One

"You are your self first supporter", a more proper way to say it



How to fix bug with endless writing of numbers using FileWriter with append argument


How to round a number to n decimal places in JavaHow do I write a correct micro-benchmark in Java?Java FileWriter with append modeHow to append text to an existing file in JavaHow do I create a file and write to it in Java?How do I fix android.os.NetworkOnMainThreadException?How to fix java.lang.UnsupportedClassVersionError: Unsupported major.minor versionDrawing an image in JScrollPane within scaleWorking on a java based chatting application using threadingCan't write number with FileWriter






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








0















I faced one problem which I’m struggling to solve.
Imagine simple game, where some object , lets call it car, remains motionless on X-axis ( x = 50 ) and is able to move only on Y-axis (up and down). At the same time, another objects are created beyond the screen at random point ( and move toward my first object ) , so their coordinates decrementing on X-axis. As soon as every object reaches my first object coordinates, some variable int scores; increments.



int scores;
if(cars.getX() == getCarPos_X() && cars.getY() != getCarPos_Y() )
scores++;


Basically this game looks like car which goes between other cars and avoid hitting, and counter scores increments every time my car pass next moving car.



So what is the problem?
I use timer which count time between repainting. All objects pass to the paintComponent where actually all graphic draw. In actionPerformed I call methods for all moves, and one method which checks if collision with another car occurred. In case of collision, game stops, and scores should be written in some txt file.
The problem is that while two objects have same coordinates, JVM write endless number of figures (scores) into the file ( I think it’s because coordinates stop decrementing and every timer interval it checks for collision and it’s == true , as game is stoped , and object remains where they are.)
So my scores in txt file looks like :



0
0
0
0


In one column.
Or it displays any score which I’ve got.
And so on...




Here is the crucial code snippet which I used



public void actionPerformed(ActionEvent e)

animate();
checkTouch();

private void animate()

//here code that creates obstacles and moves them

checkTouch()

//objects creating in some inner class Cars and add to ArrayList ( I don’t mention about it as it is beside the point )
for(Cars car : cars)

if((cars.getX() == getCarPos_X && cars. getY() == getCarPos_Y())

//boolean var which stops game
inGame = false;
writeScore();



public void writeScore()

File scoresTxt = new File("scores.txt");
FileWriter fw = null;
BufferedWriter bw = null;
try

fw = new FileWriter(scoresTxt, true);
bw = new BufferedWriter(fw);
bw.write(scores + "n");
catch (IOException e)

e.printStackTrace();
finally

try

bw.flush();
bw.close();
fw.close();
catch(IOException e)

e.printStackTrace();



public void paintComponent (Graphics g)

if(inGame)

g.drawImage(myCar, 50, 100, this);

for(Cars car : cars)

g.drawImage(obstacleCar, car.getX(), car.getY(), this);





Should you need some extra code I used, write comment and I’ll add it.
And again I need to fix bug which write endless column of numbers instead of one final score from the moment of collision.
What’s wrong with my code , and how to solve this problem?
Give me advice for simplest decision, as I’m beginner.
Thanks in advance!










share|improve this question
























  • I'd write this as an answer, but I can't be sure about it so I won't. Try doing System.exit(0), make a boolean value GameOver which is changed after the game over screen only happens once, preventing it from being written ever again, or find a way to stop the checkTouch() method from being triggered again. Maybe timer.stop() will get the spamming to stop. If you can find that none of these work, tell me.

    – FailingCoder
    Mar 9 at 3:30












  • @FailingCoder yeah , I stopped timer and it stopped spamming. But I don’t know is it best decision in terms of good programs style?

    – Vladimir Labliuk
    Mar 10 at 19:58

















0















I faced one problem which I’m struggling to solve.
Imagine simple game, where some object , lets call it car, remains motionless on X-axis ( x = 50 ) and is able to move only on Y-axis (up and down). At the same time, another objects are created beyond the screen at random point ( and move toward my first object ) , so their coordinates decrementing on X-axis. As soon as every object reaches my first object coordinates, some variable int scores; increments.



int scores;
if(cars.getX() == getCarPos_X() && cars.getY() != getCarPos_Y() )
scores++;


Basically this game looks like car which goes between other cars and avoid hitting, and counter scores increments every time my car pass next moving car.



So what is the problem?
I use timer which count time between repainting. All objects pass to the paintComponent where actually all graphic draw. In actionPerformed I call methods for all moves, and one method which checks if collision with another car occurred. In case of collision, game stops, and scores should be written in some txt file.
The problem is that while two objects have same coordinates, JVM write endless number of figures (scores) into the file ( I think it’s because coordinates stop decrementing and every timer interval it checks for collision and it’s == true , as game is stoped , and object remains where they are.)
So my scores in txt file looks like :



0
0
0
0


In one column.
Or it displays any score which I’ve got.
And so on...




Here is the crucial code snippet which I used



public void actionPerformed(ActionEvent e)

animate();
checkTouch();

private void animate()

//here code that creates obstacles and moves them

checkTouch()

//objects creating in some inner class Cars and add to ArrayList ( I don’t mention about it as it is beside the point )
for(Cars car : cars)

if((cars.getX() == getCarPos_X && cars. getY() == getCarPos_Y())

//boolean var which stops game
inGame = false;
writeScore();



public void writeScore()

File scoresTxt = new File("scores.txt");
FileWriter fw = null;
BufferedWriter bw = null;
try

fw = new FileWriter(scoresTxt, true);
bw = new BufferedWriter(fw);
bw.write(scores + "n");
catch (IOException e)

e.printStackTrace();
finally

try

bw.flush();
bw.close();
fw.close();
catch(IOException e)

e.printStackTrace();



public void paintComponent (Graphics g)

if(inGame)

g.drawImage(myCar, 50, 100, this);

for(Cars car : cars)

g.drawImage(obstacleCar, car.getX(), car.getY(), this);





Should you need some extra code I used, write comment and I’ll add it.
And again I need to fix bug which write endless column of numbers instead of one final score from the moment of collision.
What’s wrong with my code , and how to solve this problem?
Give me advice for simplest decision, as I’m beginner.
Thanks in advance!










share|improve this question
























  • I'd write this as an answer, but I can't be sure about it so I won't. Try doing System.exit(0), make a boolean value GameOver which is changed after the game over screen only happens once, preventing it from being written ever again, or find a way to stop the checkTouch() method from being triggered again. Maybe timer.stop() will get the spamming to stop. If you can find that none of these work, tell me.

    – FailingCoder
    Mar 9 at 3:30












  • @FailingCoder yeah , I stopped timer and it stopped spamming. But I don’t know is it best decision in terms of good programs style?

    – Vladimir Labliuk
    Mar 10 at 19:58













0












0








0








I faced one problem which I’m struggling to solve.
Imagine simple game, where some object , lets call it car, remains motionless on X-axis ( x = 50 ) and is able to move only on Y-axis (up and down). At the same time, another objects are created beyond the screen at random point ( and move toward my first object ) , so their coordinates decrementing on X-axis. As soon as every object reaches my first object coordinates, some variable int scores; increments.



int scores;
if(cars.getX() == getCarPos_X() && cars.getY() != getCarPos_Y() )
scores++;


Basically this game looks like car which goes between other cars and avoid hitting, and counter scores increments every time my car pass next moving car.



So what is the problem?
I use timer which count time between repainting. All objects pass to the paintComponent where actually all graphic draw. In actionPerformed I call methods for all moves, and one method which checks if collision with another car occurred. In case of collision, game stops, and scores should be written in some txt file.
The problem is that while two objects have same coordinates, JVM write endless number of figures (scores) into the file ( I think it’s because coordinates stop decrementing and every timer interval it checks for collision and it’s == true , as game is stoped , and object remains where they are.)
So my scores in txt file looks like :



0
0
0
0


In one column.
Or it displays any score which I’ve got.
And so on...




Here is the crucial code snippet which I used



public void actionPerformed(ActionEvent e)

animate();
checkTouch();

private void animate()

//here code that creates obstacles and moves them

checkTouch()

//objects creating in some inner class Cars and add to ArrayList ( I don’t mention about it as it is beside the point )
for(Cars car : cars)

if((cars.getX() == getCarPos_X && cars. getY() == getCarPos_Y())

//boolean var which stops game
inGame = false;
writeScore();



public void writeScore()

File scoresTxt = new File("scores.txt");
FileWriter fw = null;
BufferedWriter bw = null;
try

fw = new FileWriter(scoresTxt, true);
bw = new BufferedWriter(fw);
bw.write(scores + "n");
catch (IOException e)

e.printStackTrace();
finally

try

bw.flush();
bw.close();
fw.close();
catch(IOException e)

e.printStackTrace();



public void paintComponent (Graphics g)

if(inGame)

g.drawImage(myCar, 50, 100, this);

for(Cars car : cars)

g.drawImage(obstacleCar, car.getX(), car.getY(), this);





Should you need some extra code I used, write comment and I’ll add it.
And again I need to fix bug which write endless column of numbers instead of one final score from the moment of collision.
What’s wrong with my code , and how to solve this problem?
Give me advice for simplest decision, as I’m beginner.
Thanks in advance!










share|improve this question
















I faced one problem which I’m struggling to solve.
Imagine simple game, where some object , lets call it car, remains motionless on X-axis ( x = 50 ) and is able to move only on Y-axis (up and down). At the same time, another objects are created beyond the screen at random point ( and move toward my first object ) , so their coordinates decrementing on X-axis. As soon as every object reaches my first object coordinates, some variable int scores; increments.



int scores;
if(cars.getX() == getCarPos_X() && cars.getY() != getCarPos_Y() )
scores++;


Basically this game looks like car which goes between other cars and avoid hitting, and counter scores increments every time my car pass next moving car.



So what is the problem?
I use timer which count time between repainting. All objects pass to the paintComponent where actually all graphic draw. In actionPerformed I call methods for all moves, and one method which checks if collision with another car occurred. In case of collision, game stops, and scores should be written in some txt file.
The problem is that while two objects have same coordinates, JVM write endless number of figures (scores) into the file ( I think it’s because coordinates stop decrementing and every timer interval it checks for collision and it’s == true , as game is stoped , and object remains where they are.)
So my scores in txt file looks like :



0
0
0
0


In one column.
Or it displays any score which I’ve got.
And so on...




Here is the crucial code snippet which I used



public void actionPerformed(ActionEvent e)

animate();
checkTouch();

private void animate()

//here code that creates obstacles and moves them

checkTouch()

//objects creating in some inner class Cars and add to ArrayList ( I don’t mention about it as it is beside the point )
for(Cars car : cars)

if((cars.getX() == getCarPos_X && cars. getY() == getCarPos_Y())

//boolean var which stops game
inGame = false;
writeScore();



public void writeScore()

File scoresTxt = new File("scores.txt");
FileWriter fw = null;
BufferedWriter bw = null;
try

fw = new FileWriter(scoresTxt, true);
bw = new BufferedWriter(fw);
bw.write(scores + "n");
catch (IOException e)

e.printStackTrace();
finally

try

bw.flush();
bw.close();
fw.close();
catch(IOException e)

e.printStackTrace();



public void paintComponent (Graphics g)

if(inGame)

g.drawImage(myCar, 50, 100, this);

for(Cars car : cars)

g.drawImage(obstacleCar, car.getX(), car.getY(), this);





Should you need some extra code I used, write comment and I’ll add it.
And again I need to fix bug which write endless column of numbers instead of one final score from the moment of collision.
What’s wrong with my code , and how to solve this problem?
Give me advice for simplest decision, as I’m beginner.
Thanks in advance!







java animation event-handling paintcomponent filewriter






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Mar 9 at 4:43







Vladimir Labliuk

















asked Mar 9 at 3:06









Vladimir LabliukVladimir Labliuk

5319




5319












  • I'd write this as an answer, but I can't be sure about it so I won't. Try doing System.exit(0), make a boolean value GameOver which is changed after the game over screen only happens once, preventing it from being written ever again, or find a way to stop the checkTouch() method from being triggered again. Maybe timer.stop() will get the spamming to stop. If you can find that none of these work, tell me.

    – FailingCoder
    Mar 9 at 3:30












  • @FailingCoder yeah , I stopped timer and it stopped spamming. But I don’t know is it best decision in terms of good programs style?

    – Vladimir Labliuk
    Mar 10 at 19:58

















  • I'd write this as an answer, but I can't be sure about it so I won't. Try doing System.exit(0), make a boolean value GameOver which is changed after the game over screen only happens once, preventing it from being written ever again, or find a way to stop the checkTouch() method from being triggered again. Maybe timer.stop() will get the spamming to stop. If you can find that none of these work, tell me.

    – FailingCoder
    Mar 9 at 3:30












  • @FailingCoder yeah , I stopped timer and it stopped spamming. But I don’t know is it best decision in terms of good programs style?

    – Vladimir Labliuk
    Mar 10 at 19:58
















I'd write this as an answer, but I can't be sure about it so I won't. Try doing System.exit(0), make a boolean value GameOver which is changed after the game over screen only happens once, preventing it from being written ever again, or find a way to stop the checkTouch() method from being triggered again. Maybe timer.stop() will get the spamming to stop. If you can find that none of these work, tell me.

– FailingCoder
Mar 9 at 3:30






I'd write this as an answer, but I can't be sure about it so I won't. Try doing System.exit(0), make a boolean value GameOver which is changed after the game over screen only happens once, preventing it from being written ever again, or find a way to stop the checkTouch() method from being triggered again. Maybe timer.stop() will get the spamming to stop. If you can find that none of these work, tell me.

– FailingCoder
Mar 9 at 3:30














@FailingCoder yeah , I stopped timer and it stopped spamming. But I don’t know is it best decision in terms of good programs style?

– Vladimir Labliuk
Mar 10 at 19:58





@FailingCoder yeah , I stopped timer and it stopped spamming. But I don’t know is it best decision in terms of good programs style?

– Vladimir Labliuk
Mar 10 at 19:58












1 Answer
1






active

oldest

votes


















0














If your timer is started like this, or something similar, the you could cancel it when the inGame variable becomes false. Nice article on timers.



TimerTask task = new TimerTask() 
public void run()
if (!inGame)
cancel();
else
// whatever it is that you are doing now

;


You might also want to stop processing events in the actionPerformed(e) method in a similar way.



if (!inGame) 
return;





share|improve this answer























    Your Answer






    StackExchange.ifUsing("editor", function ()
    StackExchange.using("externalEditor", function ()
    StackExchange.using("snippets", function ()
    StackExchange.snippets.init();
    );
    );
    , "code-snippets");

    StackExchange.ready(function()
    var channelOptions =
    tags: "".split(" "),
    id: "1"
    ;
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function()
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled)
    StackExchange.using("snippets", function()
    createEditor();
    );

    else
    createEditor();

    );

    function createEditor()
    StackExchange.prepareEditor(
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader:
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    ,
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    );



    );













    draft saved

    draft discarded


















    StackExchange.ready(
    function ()
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55073616%2fhow-to-fix-bug-with-endless-writing-of-numbers-using-filewriter-with-append-argu%23new-answer', 'question_page');

    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    0














    If your timer is started like this, or something similar, the you could cancel it when the inGame variable becomes false. Nice article on timers.



    TimerTask task = new TimerTask() 
    public void run()
    if (!inGame)
    cancel();
    else
    // whatever it is that you are doing now

    ;


    You might also want to stop processing events in the actionPerformed(e) method in a similar way.



    if (!inGame) 
    return;





    share|improve this answer



























      0














      If your timer is started like this, or something similar, the you could cancel it when the inGame variable becomes false. Nice article on timers.



      TimerTask task = new TimerTask() 
      public void run()
      if (!inGame)
      cancel();
      else
      // whatever it is that you are doing now

      ;


      You might also want to stop processing events in the actionPerformed(e) method in a similar way.



      if (!inGame) 
      return;





      share|improve this answer

























        0












        0








        0







        If your timer is started like this, or something similar, the you could cancel it when the inGame variable becomes false. Nice article on timers.



        TimerTask task = new TimerTask() 
        public void run()
        if (!inGame)
        cancel();
        else
        // whatever it is that you are doing now

        ;


        You might also want to stop processing events in the actionPerformed(e) method in a similar way.



        if (!inGame) 
        return;





        share|improve this answer













        If your timer is started like this, or something similar, the you could cancel it when the inGame variable becomes false. Nice article on timers.



        TimerTask task = new TimerTask() 
        public void run()
        if (!inGame)
        cancel();
        else
        // whatever it is that you are doing now

        ;


        You might also want to stop processing events in the actionPerformed(e) method in a similar way.



        if (!inGame) 
        return;






        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Mar 9 at 21:25









        fedupfedup

        464




        464





























            draft saved

            draft discarded
















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid


            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.

            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55073616%2fhow-to-fix-bug-with-endless-writing-of-numbers-using-filewriter-with-append-argu%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Thal And Out Agency railway station See also References External links Navigation menuOfficial Web Site of Pakistan RailwaysArchivedOfficial Web Site of Pakistan Railwayseeexpanding ite

            Understanding generators in Python2019 Community Moderator ElectionGenerator function not working pythonFor loop not executing two timesGenerators - Printing generated valuesWhy can a python generator only be used once?What exactly do generators do?What does the “yield” keyword do?What does “list comprehension” mean? How does it work and how can I use it?sklearn Kfold acces single fold instead of for loopIs a generator the callable? Which is the generator?Apply Border To Range Of Cells Using OpenpyxlCalling an external command in PythonWhat are metaclasses in Python?What is the difference between @staticmethod and @classmethod?Finding the index of an item given a list containing it in PythonDifference between append vs. extend list methods in PythonHow can I safely create a nested directory in Python?Does Python have a ternary conditional operator?Understanding slice notationUnderstanding Python super() with __init__() methodsDoes Python have a string 'contains' substring method?

            How can I change the color of pagination dots of UIPageControl?How to change UIPageControl dotsIs there a way to change page indicator dots colorCustomize dot with image of UIPageControl at index 0 of UIPageControlNo visible @interface for 'NSObject<PageControlDelegate>' declares the selector 'pageControlPageDidChange:'How to change the color of pagination dots in UIPageControl with a different color per pagepagecontrol indicator custom image instead of DefaultChanging the colour of UIPageControl dots in MonoTouchpagecontrol selectable page visibility color?Alternative way to load ViewControllers on a UIPageControlHow to set only layer.border-color for UIpage control dots in swiftHow can I develop for iPhone using a Windows development machine?How to change the name of an iOS app?UITableView - change section header coloruipagecontrol indicator(dot)issueCustom UIPageControl dots color not changingchange the interspace between UIPageControl dotsHow to change Status Bar text color in iOSHow can I change image tintColor in iOS and WatchKitUIPageControl dots with larger space in between each dotsHow to change the color of pagination dots in UIPageControl with a different color per page