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

            Can't initialize raids on a new ASUS Prime B360M-A motherboard2019 Community Moderator ElectionSimilar to RAID config yet more like mirroring solution?Can't get motherboard serial numberWhy does the BIOS entry point start with a WBINVD instruction?UEFI performance Asus Maximus V Extreme

            Identity Server 4 is not redirecting to Angular app after login2019 Community Moderator ElectionIdentity Server 4 and dockerIdentityserver implicit flow unauthorized_clientIdentityServer Hybrid Flow - Access Token is null after user successful loginIdentity Server to MVC client : Page Redirect After loginLogin with Steam OpenId(oidc-client-js)Identity Server 4+.NET Core 2.0 + IdentityIdentityServer4 post-login redirect not working in Edge browserCall to IdentityServer4 generates System.NullReferenceException: Object reference not set to an instance of an objectIdentityServer4 without HTTPS not workingHow to get Authorization code from identity server without login form

            2005 Ahvaz unrest Contents Background Causes Casualties Aftermath See also References Navigation menue"At Least 10 Are Killed by Bombs in Iran""Iran"Archived"Arab-Iranians in Iran to make April 15 'Day of Fury'"State of Mind, State of Order: Reactions to Ethnic Unrest in the Islamic Republic of Iran.10.1111/j.1754-9469.2008.00028.x"Iran hangs Arab separatists"Iran Overview from ArchivedConstitution of the Islamic Republic of Iran"Tehran puzzled by forged 'riots' letter""Iran and its minorities: Down in the second class""Iran: Handling Of Ahvaz Unrest Could End With Televised Confessions""Bombings Rock Iran Ahead of Election""Five die in Iran ethnic clashes""Iran: Need for restraint as anniversary of unrest in Khuzestan approaches"Archived"Iranian Sunni protesters killed in clashes with security forces"Archived