1.

Solve : Problem learning Java?

Answer»

I'm trying to teach myself Java and i'm going through some tutorial i've found on the internet, but i've become stuck. It asks to write a program that when you input a full name (first, middle and last name) it output the initials. So far i have this

Quote

import java.util.Scanner;
public class Initials {
    public static void main(String[] args) {
       
        Scanner input = new Scanner (System.in);
        System.out.println("Please enter your FULL name");
        String name=input.nextLine();
             
        String index = name.substring(0,1);
        int mid = name.indexOf(" ") +1;
        int last = name.lastIndexOf(" ") +1;
       
        System.out.println(index + mid + last);

As you can probably see the output is the first INITIAL then the number of where the other to initials are. Can anyone help ??
Ive changed the middle bit to Char and it still doesnt work, i dont get it

Quote
String index = name.substring(0,1);
        char mid = (char) (name.indexOf(" ") +1);
        char last = (char) (name.lastIndexOf(" ") +1);
indexOf and LastIndexOf return an int, what you need to do is get the character at that position.

the variable "index" ought to be called 'first' to be consistent with the others. But that's more a style issue.

for the middle name, you would use the mid VALUE you have:

Code: [SELECT]String middle= name.substring(mid,mid+1);
String lastname = name.substring(last,last+1);


Naturally, you would change the final System.out.println() call to use middle and lastname instead of the numeric values.
BC, thank you very much, that worked a treat, and know i understand where is was going wrong. I makes perfect sense now, YET an hour ago its was so frustrating.

Thank you again  Quote from: reddevilggg on September 28, 2011, 04:58:53 PM
BC, thank you very much, that worked a treat, and know i understand where is was going wrong. I makes perfect sense now, yet an hour ago its was so frustrating.

Thank you again 

You're welcome

Actually even I hit a snag with that otherwise simple snippet. Since I don't USUALLY use java, I use C#. The string class in C# is similiar, and the substring method is there, but it's arguments are the start, and the length you want, whereas Java takes the start and the end indices. Had me scratching my head trying to figure out why my test (which assumed start,length) wasn't working until I looked up the method in the documentation.


Discussion

No Comment Found