I would like to complete a project that requires a name as a console input, but returns an output of that name in reverse. It should only use for-loops and strings/substrings.

I think it needs to use an array to get it done. I am right?

Below is my attempt using an array, but not correct...

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package javalessonnr;

/**
 *
 * SVW
 */

import java.io.*;
import java.util.*;

public class Main {
    
    public static void main(String[] args) {

        Scanner kbReader = new Scanner(System.in);
        System.out.print("Please enter your name. ");

        String myName = kbReader.nextLine();

        int nmeLength = myName.length();
        System.out.println(nmeLength);

        int revArr[] = new int[nmeLength];
        int arrLngth = revArr.length;
        System.out.println(arrLngth);

        String revName="";

        for(int i = 0; i < nmeLength; i++)

        {
          revName = myName.substring(nmeLength);
        }
          System.out.print(revName);
         
    }

}

Recommended Answers

All 12 Replies

No. You can use the "length" together with a for loop and combination of two calls to substring with each iteration.

I am new to Java. I am attempting to self teach myself. if you can provide that in code, I would appreciate it...thanks.

Uhm, no. I've given you hint, at least give it a try. How are you going to learn anything if I just give you the answer.

Like I said, give a try (a real try) and then post that code and we will help you to correct it.

OH...okay. Then let me give it a try. I do want to learn...

I tried. But no success. My project is to enter a name as a console input. The output should produce that name in complete reverse. Ex., enter: Gregory; output should be yrogerG. The code to produce this is to use a for-loop, and String/substring. I am stuck.

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package javalessonnr;

/**
 *
 * SVW
 */

import java.io.*;
import java.util.*;

public class Main {
    
    public static void main(String[] args) {

        Scanner kbReader = new Scanner(System.in);
        System.out.print("Please enter your name. ");

        String myName = kbReader.nextLine();

        int nmeLength = myName.length();
        nmeLength = nmeLength - 1;
        int subLength = nmeLength;
        
        String revName;

        for(int i = 0; i < nmeLength; i++)
        {
          revName = myName.substring(subLength);
          System.out.print(revName);
          subLength = subLength - 1;
        }
         
          
    }

}
myName = myName.charAt(i) + myName.substring(0, i) + myName.substring(i + 1)

I did say two calls to substring (the only thing I left out was the charAt call).

Of course it is not the most effecient process in the world, but I believe this is what your instructor was looking for. Now, study this line, and post back to me how you think it is working. See the API docs for substring (the String class, of course).

Okay. I guess all you wanted was cut-n-paste code. Well, another user for the ignore list.

I'm sorry, please don't misunderstand my delayed response. I did make the change, and it worked perfectly. Thank you. Let me say, after I made the change, I revisiting all of the notes given prior to the project to see if I missed something in my understanding. I don't believe I did. But, I wanted to get back to you with a complete understanding of the code's behavior, which required a little outside research. I did get a little busy before I had a chance. I will definitely let you know what I know about the way the code works... I want to learn this. And it would be great if I can stay in touch with you as a resource. I sincerely hope so... Thanks again...SVW

commented: Glad to hear it. +10

As I said, I had to do research, specifically on the charAt feature. It’s like a substring, and can be use to target a specific character in a string, and only that one character in the string; in this case since a variable is used it targets the character in the string based on the current value of the variable, which is based on the iteration of the for-loop.

In the first pass, the variable is equal to 0, therefore (i) is equal to
0, which points to the first character in the string. Given the input name of Jason, then (i) points to the (J) only for the myName.charAt(i) code.

Correct, charAt(0) points to the first letter (Strings are "zero-indexed", as are all arrays in Java, and a String is, essentially a char array. "zero-indexed" means the index of the first position is 0, some languages are "one-indexed").

It will then examine the myName.substring(0, i) code, and since the variable is 0, the substring method is (0, 0). Here, the static (0) should now capture the (J) and nothing else, and the variable (0) captures spaces, but it looks to me only spaces are captured for this pass. I don’t quite understand this.

Not quite, almost though. the two substring arguments are, respectively, inclusive, exclusive. That means the first argument is the actual index of the first character to be "read". The second argument is the index after the last character to be read. This means that substring(0,i) where i is 0 captures nothing as it is attempting to start after it should already have finished (so to speak) since the first index is 0 and the last index is -1 (remember the index after the last character to take). substring(i + 1) where i is the index of the last character, technically, points to an "IndexOutOfBounds", but both this condition and the "-1" (which is also an IndexOutOfBounds) are both handled gracefully by substring.

However, for the myName.substring(i + 1), the method’s value is (0 + 1). This is now pointing to ‘a’ and the remainder of the name, ie; ‘ason’. Essentially the first pass produces “Jason” for myName.

Correct. The first iteration of the loop essentially does nothing. You could start your for loop at 1 (i.e. int i = 1).


The second pass shows why this really works. The variable is equal to 1, therefore (i) is equal to (1), which points to the second character in the string “a” only for the myName.charAt(i) code. Again, it then examines the myName.substring(0, i) code, and the variable is (1), the substring method is (0, 1). Here, the static (0) now points to the “J” and the variable (i) captures the “J”. I’m not clear why both “J’s” are not captured.

Well, there is only one J. Remember one after the last char, so that substring(0, i) where i is one captures the first character and the first character only.

Now, the myName.substring(i + 1), the method’s value is (1 + 1). This is now pointing to ‘s’ and the remainder of the name, ie; ‘son’. The second pass produces “aJson” for myName.

The process repeats itself and finally produces as an output “nosaJ” for myName. I'm fairly clear how the process works and I don't think I would have been able know without your help...Thanks!

And thank you for actually studying the code. Now that you have taken the time to actually figure it out (almost, anyway) you are much more familiar with those two methods and know how to use them. Most students here, when they get code like that, cut-n-paste it and never even look at it and so don't actually learn anything, which is why we have a policy not to do that. I know that this was only a single line, and that makes it seem like a small deal, but it is the only line in the code that really means anything. You seemed to be really trying so I provided you that line, but asked you to explain it so that I knew you actually learned something.

Have fun, and Good luck with your studies. You seem to have a good head on your shoulders, so if you keep at it, you'll get it.

Wow! I haven't read your entire post, which I will do right after this reply. You didn't have to do what you did, but I am extremely grateful. I was beginning to think that you may have taken my delayed response in a way that I did not mean...In any case, I'm looking at your reply, which looks like you provided more detail to my understanding. I can't wait to read it! I am aware there are resources available to support new learners normally for a fee, my question to you is do you charge for your knowledge? I would not want you to think I have an interest to take advantage of you (or anyone for that matter), without considering this may be your business. However, I am looking to establish a resource for my development as I am learning through a manual and not a live professor...either way, once again, Thanks!!

I am happy to pass on my knowledge (as pitious as it is), I just don't like doing other's work for them. ;-)

Edit: And I expect a bit of effort. ;-)

Fair enough. And understandable. I actually enjoy the learning aspect of software development so I plan to have a ball!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.