Hello guys, i am struggling with a method i created few days already..
i created a method that prints the the char symbol of the String metho- charAt(int), but when i am trying to print it , it doesn't print anything, but i'm sure that my code is right.. could you please check it and tell me what is the problem? ,
the problematic method is : showChars(). Thank you!
posted 5 months ago
forgot to put an opening bracket at the beginning of class Letters, sorry
I hope you aren't superstitious, because I am going to direct you to line 13. Have a close look at that and work out under which circumstances the loop will run. Also, why are you using a loop and what is that method supposed to do? Come to think of it, how is the loop in line 23 supposed to work?
Why have you written that sort of method in the first place, when there are built‑in ways to print Strings and to count numbers of letters?
Much has been modified here, so let's have a look at what has been done:
It is Java convention for class names to be singular.
All the comments have been removed. The more expressive and clear your class, method and variable names are, the less need there is for comments. Once I realised that, I haven't written a comment since.
Remember to include your access modifiers on variables. Always consider, is this variable public or private? There are more modifiers, which you can read about.
Unless strictly forbidden by the requirements of the task, try to find solutions within the language to solve your task. I have completely removed the getNumOfChars() method, as you don't need to reinvent the wheel. If you search for: Java length of string, you will come across the length method, which I included in the printChars() method.
I've added some basic text to the screen, as no-one would know what to do if just given a blank cursor.
As you want to print the characters with a comma in-between, I've added a ternary statement to your output, so that it will print a comma for all the characters except the last. This is a fantastic shorthand way to have logic inside your print statement. So what we are doing is the following: If the index is less than the length of the word minus 1, then print that character at the index plus a comma, else only print the character. If the word has ten characters, we only want to print 9 commas, hence we write minus 1.
There is a shorter way of writing a for loop, called a for-each loop, which I didn't include, but you can read more about that to learn a bit more about the language.
Remember that in Java, the convention is to count from zero, so I would suggest starting your loop from zero and looping until you reach the limit of the less than conditional operator.