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

2

u/Housy5 Nooblet Brewer Mar 20 '24

If you're unsure of what for loops are.

They are basically just a while loop with a counter like this:

int count = 0;

while (count < 10) {
  System.out.println(count);
  count += 1;
}

But with the counter built in. like this:

// structure: variable; condition; increment/decrement.
for (int count = 0; count < 10; count += 1) {
  System.out.println(count);
}

1

u/[deleted] Mar 22 '24

Question: Why do we have for loop when while loop do exactly the same or vice versa? For switch and if else I can understand because switch is shorter(and some languages don't even have switch)

1

u/Housy5 Nooblet Brewer Mar 22 '24 edited Mar 22 '24

For-loops are just more convenient for iterating over things.

int[] nums = {1, 2, 3};
int sum = 0;

for (int i = 0; i < nums.length; i++) {
    sum += nums[i];
}

Compared to when you use while loops.

int index = 0;
int sum = 0;
int[] nums = {1, 2, 3};

while (index < nums.length) {
    sum += nums[index];
    index++;
}

You can also use an enhanced for-loop when you don't actually need the current index like this

int[] nums = {1, 2, 3};
int sum = 0;

for (int num : nums) {
    sum += num;
}

Then there is also streams but if you're still learning the basics of programming don't worry about this one yet. (though definitely learn it later, it's very useful)

int nums = {1, 2, 3};
int sum = Arrays.stream(nums).sum();