• Post Reply Bookmark Topic Watch Topic
  • New Topic

for-loop noob here :)  RSS feed

 
Bryce Wade
Greenhorn
Posts: 17
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hey everyone,
well i am studying java in school and am doing a test on for-loops very soon so i am now trying to make a program
that when run will print "Please enter your name." "random name inserted here"
The thing is the name, after being entered will be reversed. eg. peter ustinov = vonitsu retep
i would like some help with my code below. but I would like it if you just helped without giving me the answer just so i can learn.

my code:



i do not know how to write the for loop that will reverse the char's of the string. <-- main problem

also currently i am receiving an error in the 10th line of code

name.substring(0) = int cannot be dereferenced

Thanks for any help you can give me. should be easy considering all of the actually difficult problems on this forum
 
Anayonkar Shivalkar
Bartender
Posts: 1558
5
Eclipse IDE Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello Bryce Wade,

Welcome to CodeRanch!

First things first - start with a paper and pencil. Write down all the logical steps to reverse the String. Since you need a loop here, clearly, you would be doing it on character by character basis.

Once the correct algorithm is ready, you can easily convert it into the code.

Bryce Wade wrote: name.substring(0) = int cannot be dereferenced

This is because, name is int variable, and hence, there's no point in invoking substring method on it (rather there's no point in invoking any method on it).

I hope this helps.
 
Seetharaman Venkatasamy
Ranch Hand
Posts: 5575
Eclipse IDE Java Windows XP
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
1. you need to read string from user keyboard and for that youdefine Scanner that's fine

2. and you need to ask user to type any name; how to you output your request to user?(hint: use System class)

3. then user will type his/any name, then you need to wait until user finish his typing and hit enter, then read the line what user has been entered.use Scanner#nextLine

4.now you get the string, can you reverse the string now?
 
Bryce Wade
Greenhorn
Posts: 17
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for the replies,

I am still confused about how i should go about reversing the string.
so i understand i need to replace all of the char's, but what would the code be for the for-loop
to replace them correctly, maybe it would help me more if you could just quickly write out
the for-loop without the first part e.g. for(j = 0; j <= 10; j++) part of the code.

Thanks again for your help
 
Winston Gutkowski
Bartender
Posts: 10575
66
Eclipse IDE Hibernate Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Bryce Wade wrote:also currently i am receiving an error in the 10th line of code
name.substring(0) = int cannot be dereferenced

What it is telling you that you are attempting to call a method (substring()) on a primitive (an int). The only things that you can call methods on are objects (eg, a String), which are 'reference' types (I suggest you look it up in the Java tutorials).

Also, why are you using nextInt()? A name (or string) is made up of characters, not integers.

HIH.

Winston
 
Bryce Wade
Greenhorn
Posts: 17
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Winston,

i have fixed that, i have changed it to:

String name=kbReader.nextLine();

which i believe is correct, but now when i run the code it seems to loop? i don't know what the problem is to make it not print.

here is the current code:


not much has changed, just thought it might be easier to spot the reason for the above problem.
 
Winston Gutkowski
Bartender
Posts: 10575
66
Eclipse IDE Hibernate Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Bryce Wade wrote:I am still confused about how i should go about reversing the string...

There is more than one way, but the easiest is probably to pull all the characters from the string in question, and put them into a new character array in reverse sequence.
A couple of methods that you might find useful are String.toCharArray() and the constructor String(char[]).

HIH

Winston
 
Winston Gutkowski
Bartender
Posts: 10575
66
Eclipse IDE Hibernate Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Bryce Wade wrote:which i believe is correct, but now when i run the code it seems to loop? i don't know what the problem is to make it not print...

Well, to start with
name.substring(0);
does absolutely nothing. Firstly, name.substring(0) returns a String with the same value as name; and since you don't assign it to anything it simply disappears.
Secondly:
System.out.println(sent);
prints out the contents of sent, and what did you set that to?

Winston
 
Bryce Wade
Greenhorn
Posts: 17
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Winston,
ya the substring line is only there more as a place holder as i new i would need it within the for-loop to select the char's
and sent is instantiated a few codes above as:
String sent = "Please enter your name. ";

sadly i still have no idea about how to reverse char's cant really think of the algorithm
 
Winston Gutkowski
Bartender
Posts: 10575
66
Eclipse IDE Hibernate Ubuntu
  • Likes 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Bryce Wade wrote:sadly i still have no idea about how to reverse char's cant really think of the algorithm

Pen and paper time then. Turn OFF your computer and try it out; then translate that into a set of English (not Java) instructions. Trying to code a problem you don't understand is a recipe for disaster.

Winston
 
Campbell Ritchie
Marshal
Posts: 56546
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This may look like an advanced topic, but I think it will save you time in the long run. My suggestion:-
  • 1: Create a utility class. Look at this old post, and th links 1 2 3 in it will lead to posts about utility classes. Note this bit: “Note those examples probably have different methods from what you want.
  • 2: Give your utility class the method you do want, viz public static void swapTwoElementsInArray(char[] array, int i, int j)
  • 3: Work out what to put inside the swapTwoEtc method. You have to do that with a piece of paper. The link no 3 may give some more information.

  • Hint about swappingWhen you have got the swapping method to work, and not earlier, you write another method called public static void reverseArray(char[] array), also in the utility class. That method will call the swapTwoEtc method.
    Now you have those swapping and reversing methods, you can overload them for the other 7 types of primitive array, and one type of Object[] as parameters, if you ever need them. You can keep that utility class and add more methods to it if you need them in future.

    You can call your methods like this: MyUtilities.reverseArray(myArray); and that will reverse your array. Beware: myArray is an output parameter, so-called, that method can change the state of its argument. Your array will be reversed for ever, or at least until you make some other changes to it.
     
    Campbell Ritchie
    Marshal
    Posts: 56546
    172
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Bryce Wade wrote: . . . substring line is only there more as a place holder as i knew i would need it within the for-loop . . .
    You don’t need a substring at all.
     
    Bryce Wade
    Greenhorn
    Posts: 17
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Thanks Campbell,

    I have not gone into utility class' yet and i don't really know what a lot of the things you just said even mean.
    secondly, i know this code can be done within this class and its small from what i can remember, as some students have completed it.

    also
    just trying to think of how to do this reverse thing.
    i assume i would use the location of each character ie 0, 1, 2 = the.
    then swap the 2 with the 1. but i don't know how to do this, did i miss something in my learning of programming or is their a method?
     
    Bryce Wade
    Greenhorn
    Posts: 17
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Campbell,

    the reason i have the substring code at all is because the question says i need one (or should use it).
    the question says i need to use the string method, substring(...), and that it should print in lower case (that i can do )
     
    fred rosenberger
    lowercase baba
    Bartender
    Posts: 12563
    49
    Chrome Java Linux
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Note that you don't have to swap/move any characters anywhere. Say I want to print the numbers 1-10. I could write this:


    If i want to print the number from 10 to 1, I could write this:




    The point being, you can iterate from the front to the back, or from the back to the front...

    Edit - So I was thinking...DO you need to reverse the string? Or do you just need to PRINT the string in reverse order? There is a difference.
     
    Jeff Verdegan
    Bartender
    Posts: 6109
    6
    Android IntelliJ IDE Java
    • Likes 1
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Bryce Wade wrote:
    also
    just trying to think of how to do this reverse thing.
    i assume i would use the location of each character ie 0, 1, 2 = the.
    then swap the 2 with the 1. but i don't know how to do this, did i miss something in my learning of programming or is their a method?


    You need to follow Winston's advice. Your problem at the moment has nothing at all to do with Java or with programming. Your problem right now is simply one of describing the steps.

    So, as suggested, get a pencil and paper. Draw out boxes with letters in them, and number the boxes, such as:


    Then write down the exact, simple, precise steps needed to reverse them.

    You might start with somthing like, "1. Place the character in box 0 into box 4." and continue like that. Then you might realize that that only works if you know ahead of time exactly how many characters there will be, and that it's very repetitive, and that you could change it to something like, "1. For each box, 'i', do such and such with the char in box i and such and such with the char in some other box relative to i."

    It may take you a few passes to get it, but that's normal. Once you think you've got those steps down pat, translating them to Java should be straightforward.

    Don't guess--you should know what each line of your code does and why it's there. And if you do have to guess because you're not sure of something, write a tiny program that just does that one thing you're guessing at, and tweak it until you understand how it works. It may seem like that will take a long time, but I promise, it saves time in the long run, and leads to code you actually understand. I've been programming professionally for nearly 20 years, and I don't think a day goes by that I don't write a very short program just to test some concept I'm not totally sure about.
     
    rohit chavan
    Ranch Hand
    Posts: 133
    Hibernate Java Oracle
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Above post explains the solution in the best possible way.
    "Pen and pencil and logic" are your long term friends, coding languages can be many.
    All the best!
     
    Campbell Ritchie
    Marshal
    Posts: 56546
    172
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    You did say originally you needed the name reversed. Dividing the task into smaller steps is the best way to solve it, but as people have mentioned, you can display the String in reverse order without actually reversing it.
     
    Bryce Wade
    Greenhorn
    Posts: 17
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Thanks everyone that has posted a reply.
    although i am still confused about how to do this. maybe it would be easier if someone told me
    how to do this. and i just write the code that will do it. i am only saying this because so many people
    have given suggestions and i am still herping and derping over here about this
     
    Campbell Ritchie
    Marshal
    Posts: 56546
    172
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    No, we don’t give out the answer; you would be found out and would get a 0 in your assessment.

    We have given you all sorts of hints. It is not a difficult task, as long as you go round it the right way. The right way is to work out on paper what you would do, and divide it into small bits. Each “bit” becomes a method, and the methods call each other.
    The wrong way to do it is to write lots of code and try tweaking it in the hope it will get better. The wrong way is to try to squeeze everything into the main method.

    And I still cannot think why you are supposed to use substrings to reverse a String. You might use substrings to display a String in reverse order, which is a simpler task than actually reversing it. But I wouldn’t use substrings myself, not even to print “Campbell” as “llebpmaC”. I would get the String into a char[], which is a very simple task if you go through the String class method summary and read the names of the methods. Then you can reverse the array, or (to display), you could simply print it out backwards.
     
    Bryce Wade
    Greenhorn
    Posts: 17
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    to campbell,
    i am not getting assessed on this. its just to better myself, we have already been over this but i didnt quite get it so i thought i would seek outside help (my teacher struggles with coding and speaking english)
    also i think the task was to just print it in reverse. but the program must work with any text which makes it actually difficult.

    My class is using Blue pelican java as our questions and our learning source. this programming is located in i think chapter 9 we are up to chapter 37 Exceptions! this is why i am seeking help (the book goes to 50 or 40)
     
    Winston Gutkowski
    Bartender
    Posts: 10575
    66
    Eclipse IDE Hibernate Ubuntu
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Bryce Wade wrote:to campbell,
    i am not getting assessed on this. its just to better myself...

    All the more reason to do it yourself then.

    I know it's a pain, but you will learn an awful lot more if you follow some of the good advice you've been given (particularly Jeff's idea of using diagrams - a picture is often worth a thousand words) than if someone simply gives you the answer.

    A couple of things to remember:
  • Arrays (and Strings; and, in fact, most collections) in Java "know" their size.
  • There are 2 basic ways to do what you want:
  •    1. Copy the contents of your String/array to a new one in reverse sequence.
       2. Reverse the contents in place (hint: think about swapping pairs of characters).
       and you may find one method easier to visualize than the other.

    HIH - and I say again: Turn your computer OFF until you really understand the problem.

    Winston
     
    fred rosenberger
    lowercase baba
    Bartender
    Posts: 12563
    49
    Chrome Java Linux
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Winston Gutkowski wrote:A couple of things to remember:
  • Arrays (and Strings; and, in fact, most collections) in Java "know" their size.
  • There are 2 basic ways to do what you want:
  •    1. Copy the contents of your String/array to a new one in reverse sequence.
       2. Reverse the contents in place (hint: think about swapping pairs of characters).

    ummm...I still vote for three ways:
    3) traverse the existing string from the end and move back towards the front.
     
    Winston Gutkowski
    Bartender
    Posts: 10575
    66
    Eclipse IDE Hibernate Ubuntu
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    fred rosenberger wrote:3) traverse the existing string from the end and move back towards the front.

    Yup, quite right.

    Winston
     
    • Post Reply Bookmark Topic Watch Topic
    • New Topic
    Boost this thread!