r/javahelp • • 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

21 comments sorted by

View all comments

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:

String a = “”;
String b = “x”;
String c = a + b;

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.

2

u/Grand-Illustrator397 Mar 21 '24

you know what, I think that is my main issue. I don't know how to properly read While methods. I watched plenty youtube videos trying to learn about it but all the 'While' scenarios these instructors used are very different from my Professors.

Because I can easily solve math problems, use If statements, use Switch Statements, and so on....

But I just dont get the point of 'While' seems very useless. I also hate using strings/substring lol. .

1

u/jlanawalt Mar 21 '24

If you have some extra time, the MOOC.fi suggested in the channel sidebar will drill you on while loops over a series of guided exercises.