1

I don't get this to work. This is OOP. I am supposed to get the (x,y) coordinates in a grid when moving it up, down, left or right. I need the toString to always update for every move I take. I would prefer using arrow keys in the keyboard, but I don't know how. If someone know that it would be nice for the program. I must be able to - for example - press up, then down, then up without it stopping.

    package stateandbehavior;
    import java.util.*;
    public class Location {

        int x;
        int y;
    
        public void up() {
        boolean run = true;
        while (run) {   
        Scanner tast = new Scanner(System.in);
        String tas = tast.nextLine();
        if (tas == "W" || tas == "w") {
            y-=1;
        }else {
            run = false;
        }
        }
    }
    
    public void down() {
        boolean run = true;
        while (run) {
        Scanner tast = new Scanner(System.in);
        String tas = tast.nextLine();
        if(tas == "S" || tas == "s") {
            y+=1;
        } else {
            run = false;
        }
        }
        
    }
    
    public void right() {
        boolean run = true;
        while (run) {
        Scanner tast = new Scanner(System.in);
        String tas = tast.nextLine();
        if (tas == "D" || tas == "d") {
            x+=1;
        }else {
            run = false;
        }
        }
    }
    
    public void left() {
        boolean run = true;
        while(run)
        Scanner tast = new Scanner(System.in);
        String tas = tast.nextLine();
        if(tas == "A" || tas == "a") {
            x-=1;
        }else {
            run = false;
        }
    }
    
    public int getX() {
        return x;
    }
    
    public int getY() {
        return y;   
    }
    
    public String toString() {
        return "(" + x + ","+ y + ")";
    }
    
    public static void main(String[] args) {
        Location Loc = new Location();
        Loc.up();
        Loc.down();
        Loc.right();
        Loc.left();
        Loc.getX();
        Loc.getY();
        System.out.println(Loc);    
    }
}
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Codeman
  • 25
  • 3
  • 1
    Your code is horrible. a) it's wrong. Wrong concept. Ill post a solution. b) the formatting (especially intendation) is really bad. Use Eclipse or IntelliJ, use the formatting features they bring. c) the code has syntactical/structural errors. Curly brackets placed wrong. d) naming convention is lowerCase names for objects, i.e. it should be `Location loc = new Location()` – JayC667 Jan 16 '21 at 03:32

2 Answers2

0

Here's my first solution, using the WASD keys with line input (need to hit enter):

package stackoverflow.notmoving;

import java.util.Scanner;

public class Location2 {

    private int x;
    private int y;

    public void up() {
        y -= 1;
    }
    public void down() {
        y += 1;
    }
    public void right() {
        x += 1;
    }
    public void left() {
        x -= 1;
    }

    public int getX() {
        return x;
    }
    public int getY() {
        return y;
    }

    @Override public String toString() {
        return "(" + x + "," + y + ")";
    }



    public static void main(final String[] args) {
        final Location2 loc = new Location2();

        final Scanner scanner = new Scanner(System.in);

        firstLoop: while (true) {
            System.out.print("Please enter new direction: ");
            final String inputRaw = scanner.nextLine();
            final String input = inputRaw == null ? "" : inputRaw.toLowerCase();
            switch (input) {
                case "w": {
                    loc.up();
                    break;
                }
                case "a": {
                    loc.left();
                    break;
                }
                case "s": {
                    loc.down();
                    break;
                }
                case "d": {
                    loc.right();
                    break;
                }
                case "e": {
                    System.out.println("Exiting input loop");
                    break firstLoop;
                }
                default:
                    /* ignore all other keys/strings */
            }
            System.out.println("New location: " + loc);
        }

        System.out.println("App ended with location: " + loc);
    }

}

Real arrow keys solution coming in a second answer

JayC667
  • 2,418
  • 2
  • 17
  • 31
0

Second solution. Uses Java Swing to build a GUI.

Problem is with current Java console support, getting the KeyCodes of the keys that are pressed ist not possible. You COULD use a library for a listener: I like using JNativeHook for that. You COULD also trick your OS in handling you the keycodes, thats very hackish. So in the end, games and whatnot always use real GUI windows, and with them comes easy input handling:

(use together with the Location2 class I provided in the other answer)

package stackoverflow.notmoving;

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;

public class LocationWindow extends JFrame {
    private static final long serialVersionUID = -6515573336353025277L;



    private final JLabel    cLabPosition    = new JLabel("Position: ");
    private final JButton   cBtnControl     = new JButton("Focus this for controls...");

    private final Location2 myLocation = new Location2();

    public LocationWindow() {
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setLayout(new BorderLayout());
        setTitle("Simple GUI");

        add(cLabPosition, BorderLayout.NORTH);

        cBtnControl.addActionListener(e -> buttonPressed(e));
        cBtnControl.addKeyListener(new KeyAdapter() {
            @Override public void keyPressed(final KeyEvent pE) {
                LocationWindow.this.keyPressed(pE);
            }
        });
        add(cBtnControl, BorderLayout.CENTER);

        pack();
    }



    protected void keyPressed(final KeyEvent pE) {
        System.out.println("LocationWindow.keyPressed(" + pE + ")");
        switch (pE.getKeyCode()) {
            case (KeyEvent.VK_UP): {
                myLocation.up();
                break;
            }
            case (KeyEvent.VK_LEFT): {
                myLocation.left();
                break;
            }
            case (KeyEvent.VK_DOWN): {
                myLocation.down();
                break;
            }
            case (KeyEvent.VK_RIGHT): {
                myLocation.right();
                break;
            }
            case (KeyEvent.VK_ESCAPE): {
                dispose();
                break;
            }
            default:
                /* ignore */
        }
        cLabPosition.setText("Position: " + myLocation);
    }

    private void buttonPressed(@SuppressWarnings("unused") final ActionEvent pE) {
        cLabPosition.setText("You have taken control!");
        cBtnControl.setText("Controlling...");
    }

    public static void main(final String[] args) {
        final LocationWindow l = new LocationWindow();
        l.setVisible(true);
    }

}

You will see lots of similarities between the two.

JayC667
  • 2,418
  • 2
  • 17
  • 31
  • Thank you. For this function to work i always need to hit enter when pushing WASD. How can i make it notice it by its own and increase its numbers or decrease – Codeman Jan 16 '21 at 18:06
  • 3 possibilities: 1) do not have any focusable controls in the form, so all events fall 'through' to JFrame itself. Instead of `cBtnControl.addKeyListener(...);` you could then write `this.addKeyListener(...);` (with 'this' being the LocationWindow/JFrame. 2) You could register Key Events with a KeyListener like in `https://stackoverflow.com/questions/58713715/how-to-get-a-key-event-in-a-java-swing-jframe-instance-which-has-many-jtextfield` and 3) you could use a global listener that listens to all Key Events on the OS, for example JNativeHook. From (1) to (3) hackyness increases exponentially. – JayC667 Jan 17 '21 at 08:51
  • And I think your comment here targeted the other example. As I stated in this example, using Java System.in/console will NOT get you events UNLESS you pressed enter. So the console does not suffice, you would need hacks or libraries such as JNativeHooks. – JayC667 Jan 17 '21 at 08:57