Это код, который я создал, чтобы завершить sh какой-то другой мой проект. Я пытался сделать это некоторое время, и я думаю, что переменные, объявленные внутри циклов, не доступны, если их слишком много, в то время как циклы глубоки, поэтому я не думаю, что смогу выполнить это с помощью простого средства. Было бы очень полезно, если бы кто-то мог показать мне, почему этот код не дал мне того результата, на который я надеялся.
char letter, D;
int lengthString, position, positionInCat, textLength, repetitions;
String cat = "cat", newCat = "", text, reversingText, reversedText = ""; //Goal: change "cat" to "cad"
D = 'D';
lengthString = cat.length();
position = 0;
positionInCat = 2; // what I am looking to alter. For example
//position in cat = 2. 2 becomes a D or any other character. The output should //be: cDt
reversingText = cat;
repetitions = reversingText.length();
textLength = reversingText.length() - 1;
while (repetitions > 0) { // reverses the text
letter = reversingText.charAt(textLength);
reversedText = reversedText + letter;
repetitions--;
textLength --;
}
letter = ' ';
cat = reversedText; // applies the reversion
while (lengthString > 1) {
while (lengthString != positionInCat) { // changes cat to what I want the outcome to be: cDt
letter = cat.charAt(position);
newCat = newCat + letter; // rebuilding CAT
position++;
lengthString--;
}
newCat = newCat + D; // Altering the cat
position++;
lengthString--;
while (lengthString > 0) {
letter = cat.charAt(position);
newCat = newCat + letter;
position++;
lengthString--;
} }
letter = ' ';
cat = newCat;
reversingText = cat; // giving the reversingText its work
repetitions = reversingText.length();
textLength = reversingText.length() - 1;
while (repetitions > 0) { // unreverses the reversed text
letter = reversingText.charAt(textLength);
reversedText = reversedText + letter;
repetitions--;
textLength --;
}
cat = reversedText; // applies the reversion
System.out.print(cat); // what my work should have given me is cDt
}
} // This is my attempt at it, but I can only get out "taccDt" with it, instead of "cDt"