This program asks the user for a word and then the length of the first part to be printed.
My Code
import java.util.Scanner;
public class ReversingText {
public static String reverse(String text) {
// write your code here
// note that method does now print anything, it RETURNS the reversed string
int i =text.length() -1;
String revText = "";
while ( i > -1){
revText = revText + text.charAt(i);
i--;
}
return revText;
}
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
System.out.print("Type in your text: ");
String text = reader.nextLine();
System.out.println("In reverse order: " + reverse(text));
}
}
Model Code
import java.util.Scanner;
public class ReversingText {
public static String reverse(String text) {
// write your code here
// note that method does now print anything, it RETURNS the reversed string
// First we create an empty string
String result = "";
// then the rest is copied to it one by one at reverse order
int i = text.length() - 1;
while (i >= 0) {
result += text.charAt(i); // same as result = result + text.charAt(i);
i--;
}
return result;
}
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
System.out.print("Type in your text: ");
String text = reader.nextLine();
System.out.println("In reverse order: " + reverse(text));
}
}
Comments
Relatively the same although I forgot to use =+ to in the loop to add the characters to the end of revText whereas the Model Code does to add to result.