PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Wednesday, July 20, 2022

[FIXED] How do I add to my int variables when I press a key?

 July 20, 2022     console.readkey, integer, variables     No comments   

Issue

The title summed up what I am trying to figure out.

I am trying to get my int variables to increase and/or decrease depending on what directional key I press.

int x;
int y;
x = 0;
y = 0;

Console.WriteLine("X:" +x + "Y:" +y);

while (Console.Readkey().Key == ConsoleKey.UpArrow)
{
y = +1;
}

If I press the Up arrow nothing happens, if I press any other directional keys it will exit the Console. I fell that I am on the right track because of that alone.

Any help is awesome.


Solution

Here you go. I've written this in a way that I'm assuming does what you want it to do.

int x = 0; 
int y = 0; 

Console.WriteLine("X:" + x + "Y:" + y);

while (true)
{
    ConsoleKey key = Console.ReadKey().Key;
    Console.Clear();
    if (key == ConsoleKey.UpArrow)
    {
        y += 1;
        Console.WriteLine("X:" + x + "Y:" + y);
    }
    else if (key == ConsoleKey.DownArrow)
    {
        y -= 1;
        Console.WriteLine("X:" + x + "Y:" + y);
    }
    else if (key == ConsoleKey.RightArrow)
    {
        x += 1;
        Console.WriteLine("X:" + x + "Y:" + y);
    }
    else if (key == ConsoleKey.LeftArrow)
    {
        x -= 1;
        Console.WriteLine("X:" + x + "Y:" + y);
    }
}

It saves the current key in ConsoleKey key and then checks which direction was pressed, and modifies x or y as necessary.

Note that I also added a Console.Clear() so everything prints neatly instead of repeatedly one after another.



Answered By - Mister246
Answer Checked By - Clifford M. (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing