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.
4
Mar 21 '24 edited Mar 21 '24
What exactly is this code supposed to do? Pretty tough to read. Also .substring() is a doozy of a method of get used to since the first index is included, and the second is excluded. (I think. 15+ years of Java. I still read the documentation lol)
String is just a built-in, super convienant array of 'char'. They're actually pretty heavy on your computer. Try adding an array of integers to another, like ""+"" and you'll notice how nice this is for the concatenation of strings.
StringBuilder is the best way to simplify the concatenation. If you ever get around to decompile your compiled .class files, you'll see that the compiler actually converts all the ""+"" to the StringBuilder form. The compiler does a lot of optimizations like this for you.
^ important to note that inside a loop, it'll make a new StringBuilder each iteration. So declare it above the loop. Will make your loops MUCH faster.
1
u/Grand-Illustrator397 Mar 21 '24
I have solved it now, but I feel guilty because i used GPT to help me, but here is what the program was supposed to do..
The loop below is intended to collect all characters that occur more than once in a given string. When you try it out with a string such as "Mississippi", you will note that letters that occur three or more times are collected more than once. Modify the loop so that each repeated letter is collected exactly once.
For example, when s is "Mississippi", result should be "isp" and not "issisip"2
Mar 21 '24
For something simple like this, GPT is okay. It should have printed out good comments for it. If you go into Bing's search bar with Co-Pilot (powered by GPT 4), it should be able to print out a decent visualization of what it's doing in each iteration, too. Just make sure you understand what's going on in each loop iteration. Using String.toCharArray() would help a lot, too. This way, you're just iterating through an array like normal. No reliance on .substring(...) or anything. Your teacher may of wanted you to use substring() though. Idk.
You're in Java, so don't be afraid to name your variables with pretty large names that describe exactly what they are. result->collectedRepeatedChars. remain-> remainingUnparsedChars. You can name them whatever you like, but naming variables with detail can make your code much easier to figure out. It'll save you from having to comment as much, too. Some people love comments... I don't. To each their own.
You're gonna be mad when in about a week or so, your teacher shows you what 'Set's are. Pretty much 'List's, but it can only have unique items; no repeats. They would have solved half your problem for you. It's good to be able to hardcode these things yourself, though, and not be completely reliant on pre-made libraries that Java has. Don't be afraid to go into some source code and learn from it, though. Learn, not copy; sometimes it's the same thing, though.
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. .
3
u/hibbelig Mar 21 '24
Prime example for while loops:
Write a program that asks the user to enter a numbers, as many as the user wants. When the user enters the number zero that’s a sign to stop. Then print the sum of all the numbers entered by the user.
The whole loop is ideal for this, any other construct is going to be inconvenient.
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.
7
u/Cengo789 Mar 20 '24
You could take a look at the String api documentation if you are not sure what a method does exactly. String s = "" is an empty string, yes. Adding an empty string to something else does nothing (except to cause the other objects .toString() method being called, if necessary).
4
Mar 20 '24
When you need to manipulate Strings inside a loop consider using StringBuilder, it is more efficient as it mutates the inner character array and only creates the final String after you finished your algorithm.
3
u/Housy5 Nooblet Brewer Mar 21 '24
Since they still struggle with for loops and string manipulation. I doubt they should be caring about optimizing performance in a loop that probably wont go through enough iterations for it to really matter in the first place.
1
1
u/amfa Mar 21 '24
afaik the compiler will use StringBuilder if possible on his own.
Don't if this will be the case here but in general it should not matter that much.
1
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
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();
2
u/DelayLucky Mar 21 '24
Sorry for going off topic. Is it what Reddit do not formatting code indentations well? I haven't posted any code yet so no idea if this is a platform thing. But if easy, strongly recommend to format the code so it's easier to read.
Nvm if Reddit is just like that.
1
u/chet714 Mar 21 '24
Not off topic at all. This sub's sidebar addresses it and links to a guide but many don't take the time to read it. I've seen worse, at least OP used a code block. :D
1
u/ShoulderPast2433 Mar 23 '24
Its nothing really complicated - all the problems stem from the +1 -1 errors (for example str.substring(1,3) you don't know if 3 is included or nor, or which exactly letter it will be because indexing starts at 0 and we have been counting from 1 for our entire life)
There is nothing we can explain you - you just need to practise, and your brain will learn how it works.
•
u/AutoModerator Mar 20 '24
Please ensure that:
Your code is properly formatted as code block - see the sidebar (About on mobile) for instructions
You include any and all error messages in full
You ask clear questions
You demonstrate effort in solving your question/problem - plain posting your assignments is forbidden (and such posts will be removed) as is asking for or giving solutions.
Trying to solve problems on your own is a very important skill. Also, see Learn to help yourself in the sidebar
If any of the above points is not met, your post can and will be removed without further warning.
Code is to be formatted as code block (old reddit: empty line before the code, each code line indented by 4 spaces, new reddit: https://i.imgur.com/EJ7tqek.png) or linked via an external code hoster, like pastebin.com, github gist, github, bitbucket, gitlab, etc.
Please, do not use triple backticks (```) as they will only render properly on new reddit, not on old reddit.
Code blocks look like this:
You do not need to repost unless your post has been removed by a moderator. Just use the edit function of reddit to make sure your post complies with the above.
If your post has remained in violation of these rules for a prolonged period of time (at least an hour), a moderator may remove it at their discretion. In this case, they will comment with an explanation on why it has been removed, and you will be required to resubmit the entire post following the proper procedures.
To potential helpers
Please, do not help if any of the above points are not met, rather report the post. We are trying to improve the quality of posts here. In helping people who can't be bothered to comply with the above points, you are doing the community a disservice.
I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.