0

Need some help solving a code challenge (Camel to Snake) (Java)

I'm getting all of the trials correct except the fifth one (it won't let me know what it is) My code is below, I know it's messy I'm still pretty new to Java but I added some comments import java.util.Scanner; public class Program { public static void main(String[] args) { Scanner sc = new Scanner(System.in); char[] camel = sc.nextLine().toCharArray(); // original input String fin = ""; // final string to be used int x = 0; // used to tell if the following code is the first instance or not for (char i:camel){ if (Character.isUpperCase(i) && x>0){ fin+="_"+Character.toLowerCase(i); } // adds _c for C to final if its uppercase and not the first time else { fin+=i; //adds original character }; x++; }; System.out.println(fin); } }

30th Jun 2023, 6:46 AM
Tanner
Tanner - avatar
2 ответов
+ 1
Here's an updated version of your code: 👇 import java.util.Scanner; public class Program { public static void main(String[] args) { Scanner sc = new Scanner(System.in); char[] camel = sc.nextLine().toCharArray(); String fin = ""; int x = 0; for (char i : camel) { if (Character.isUpperCase(i)) { if (x > 0) { fin += "_"; } fin += Character.toLowerCase(i); } else { fin += i; } x++; } System.out.println(fin); } }
30th Jun 2023, 7:19 AM
Kakashi はたけ
Kakashi はたけ - avatar
+ 1
It will also work. 👇 public final class CamelToSnake { public static void main(String[] args) { System.out.println( new java.util.Scanner(System.in) .nextLine() .replaceAll("(?<=[^//b^])([A-Z])", "_$1") .toLowerCase() ); } }
30th Jun 2023, 7:21 AM
Kakashi はたけ
Kakashi はたけ - avatar