0
Reverse string test case won't approve my code even if the expected output is the same as my output
my code is this, try it in the reverse string Java array challenge, can anyone get why it won't pass? import java.util.Scanner; public class Program { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); String text = scanner.nextLine(); char[] arr = text.toCharArray(); //your code goes here int size = arr.length; char[] reversedArr = new char[size+1]; for(int i = 0; i<size; i++){ reversedArr[size-i]=arr[i]; } System.out.println (String.valueOf(reversedArr) ); } } Thank you in advance
3 Respostas
+ 3
Zephi
Your issue is that the size of your new array 'reversedArr' is larger than the input string by 1. You can remove the +1 and then in your loop -1 in the index to maintain the correct size.
reversedArr[size-1-i]
You could also change your loop as Malek Alsset has it.
I don't think you even need to create a new array really, but can just print() each character of the input string in reverse to achieve the reversed output of the string.
+ 8
you can also do this task without using an additional char array:
import java.util.Scanner;
public class Program
{
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String text = scanner.nextLine();
char[] arr = text.toCharArray();
//your code goes here
for (int x = arr.length - 1; x >=0; x--)
{
System.out.print(arr[x]);
}
}
}