iProgramIt
iProgramIt

Reputation: 54

Simple Substring Issue

My teacher wants us to make a letter 'o' move around the console. The letter 'o' has been coded to appear in the center of the console screen. I have already created the movingRight and movingDown methods but I'm having difficulty creating the movingLeft and movingUp methods. Here is my code:

import java.util.Scanner;

public class Main {

static String letter = "\n\n\n\n                                                                               O";
String whenmovingup = letter.substring(0, 1);
char whenmovingleft = letter.charAt(letter.length() - 2);

public static void main(String[] args) {

    Scanner input = new Scanner(System.in);

    System.out.print(letter);
    input.nextLine();

    if (input.equals("left")) {
        movingLeft();
    }
    if (input.equals("right")) {
        movingRight();
    }
    if (input.equals("up")) {
        movingUp();
    }
    if (input.equals("down")) {
        movingDown();
    }

}

    public static void movingRight(){
        letter = " " + letter;
    }
    public static void movingDown(){
        letter = "\n" + letter;
    }
    public static void movingLeft(){
        letter.remove(whenmovingleft);
    }
    public static void movingUp(){
        letter.remove(whenmovingup);
    }
}

I'm having an issue with removing the whenmovingfeft and whenmovingup substrings from my original string letter. It's giving an error ('The method remove(char) is undefined for the type String'), and I'm not sure what needs to be done.

Does anyone know how this can be resolved? Thanks in advance for all responses.

Upvotes: 0

Views: 79

Answers (1)

Greg Hewgill
Greg Hewgill

Reputation: 993095

There is no remove method for a string. However, there is a replace method that may do what you want. Note that it does not modify the string object, but it returns a new string. So you would do:

letter = letter.replace(whenmovingup, "");

Note that there are two slightly different overloads of replace which do different things depending on whether you ask it to remove a String or char. The replace(String, String) method replaces one occurrence, while the replace(char, char) replaces all occurrences. You want just one, so declare whenmovingleft as a String and initialise it appropriately.

Upvotes: 1

Related Questions