How to start outputting a new line and then returning to the previous java line

I am doing an English program for braille. This is how i do it

    if(letter_saver.contains("a")){
            System.out.println("|. |");
            System.out.println("|..|");
            System.out.println("| .|");

print out

|. |  //but i need to be able to come back to this line to do the next letter  
|..|  
| .| 

Instead, print it here.

+4
source share
2 answers

You cannot accomplish this with System.out.print.

Instead, you need another variable to hold the text while working on it.

I would recommend using a string array (or ArrayList if you don't know how many lines will be in advance), with each entry corresponding to a line of text.

ArrayList<String> lines = new ArrayList<String>();
lines.add("|. |");
lines.add("|..|");
lines.add("| .|");

Thus, you can easily return to editing the previous line as follows:

lines.set(0, lines.get(0).concat("text to add"); // Edit a previous line

Then, when you are ready to display the results:

for(String s : lines)
    System.out.println(s);
+4
source

, . . . , .

public class Braille {
    char letter;
    String lineOne;
    String lineTwo;
    String lineThree;
    //More variables if necessary

    public Braille(char letter, String lineOne, String lineTwo, String lineThree){
        this.letter = letter;
        this.lineOne = lineOne;
        this.lineTwo = lineTwo;
        this.lineThree = lineThree;
    }
    public char getLetter(){
        return letter;
    }
    public String getLineOne(){
        return lineOne;
    }
    public String getLineTwo(){
        return lineTwo;
    }
    public String getLineThree(){
        return lineThree;
    }
}

.

Braille a = new Braille('a', "|. |", "|..|", "| .|");
//A data structure to store the letters is necessary.
ArrayList<Braille> brailleLetters = new ArrayList<Braille>();
brailleLetters.add(a);

public Braille getLetter(char letter){
    int index = 0;
    while(index < brailleLetters.size()){
        if(brailleLetters.get(index) == letter){
            return brailleLetters.get(index);
        index++;
    }
    return null;
}

getLine. , .

String convertString = "Test";
String lineOne = "";
String lineTwo = "";
String lineThree = "";
int index = 0;
while(index < convertString.length){
    lineOne += getLetter(converString.getCharAt(index)).getLineOne();
    index++;
}
//More loops needed based on number of lines.

, - .

0

Source: https://habr.com/ru/post/1694155/


All Articles