r/javahelp • u/Grand-Illustrator397 • Mar 20 '24
I hate strings
import java.util.Scanner;
public class Main {
public static void main(String[]args){
Scanner in = new Scanner(System.in);
String s = in.next();
String rest = s;
String result = ""; // empty string?
int i = 0;
while (rest.length() > 0)
{
String first = rest.substring(0,1); //extracts first character of 'rest' string
rest = rest.substring(1); // now it removes the first character?
if (rest.contains(first))
{
result = result + first; // what is being added if 'result' is empty
}
}
System.out.println(result);
}
}any video recomms for this type of use for loops and strings?? I tried using a table chart to understand a little better but it didnt work out for me, and i still dont understand how it works. Help would be appreaciated.
0
Upvotes
4
u/hibbelig Mar 21 '24
My suggestion for tackling this is the scientific method: create a hypothesis of what you think happens, then verify what really happens.
Sometimes you don’t have a hypothesis. That’s also fine, write a little code to see what happens.
For example that last question:
Then you can print c. Now you know what happens when that string is empty.
About the question whether it removes the first character: print rest before the operation and after and then you know.