i have a .csv file contain some name as below:

William Shakespeare
charlie chaplin
david Copperfield

and i'm supposed to write a java program that will turn the input above into the output below:

WS
cc
dC

but i still couldn't get the output that i want, i wanna ask is there anything wrong with my code below?

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.*;
import java.io.*;

public class tryname {

  public static void main(String[] args) {

    tryname obj = new tryname();
    obj.run();

  }

  public void run() {

    BufferedReader reader = null;
    char tempname;
    //int point =0;
    String Fullname= "", Initials = "" ;
    String cvsSplitBy = "\n";

    try {

        File csvfile = new File ("Sample2.csv");
        reader = new BufferedReader(new FileReader(csvfile));
        String line = "";   
        //String s;
        while ((line = reader.readLine()) != null) {

            // use comma as separator
            String[] name = line.split(cvsSplitBy); 
            Fullname = name[0];
            for(int i = 0; i < Fullname.length(); i++){ 
                //Initials = name [i];
                tempname= Fullname.charAt(i);
                if(tempname == ' ')
                {
                     //Fullname += name.charAt(i);
                     Initials += Fullname.charAt(i+1);
                     //point= i+1;
                }
            }
            System.out.println(Initials);

        }

Recommended Answers

All 15 Replies

you're not following regular naming conventions, for one.
as for your problems: it would be easier to spot if you also mentioned what it is doing wrong.

does it compile? does it thrown an exception? do you get the wrong output (and which)? ...
but why are you looping over the chars to get the different names? why not using the split method there as well?

sorry,i forgot to mention about that.it compile and there's no exception error. the output is wrong. it gave this :

S
Sc
ScC

instead of the one i mentioned above. i thought of looping it char by char to check whether the next char is a '' or not. if it's a ' ' then the next char will be selected and assigned to a variable and the next char selected will be concatenated with the char selected earlier. that's is what i thought. i'm not very good in programming so i refer to internet when i'm doing this. please guide me or share with me your thought for this problem. thank you.

Your code is almost right - you have the right pieces but the order is a bit messed up.
Read each line of the file,
split each line into words (ie use split with the default separator of a space),
then use chatAt to get the first letter of each word.

i've just eliminate some of the unused variable and some stuff hopefully it look more presentable. about the split with the default separator of space i used it this way String[] name = line.split("\n"); is it wrong?

public static void main(String[] args) {

    tryname obj = new tryname();
    obj.run();

  }

  public void run() {

    BufferedReader reader = null;
    String Fullname= "", Initials = "" ;    
    try {

        File csvfile = new File ("Sample2.csv");
        reader = new BufferedReader(new FileReader(csvfile));
        String line = "";   
        while ((line = reader.readLine()) != null) {
            String[] name = line.split("\n");   
            Fullname = name[0];
            for(int i = 0; i < Fullname.length(); ++i){ 
                if(Fullname.charAt(i) == ' ')
                {
                     Initials += Fullname.charAt(i+1);
                }
            }
            System.out.println(Initials);
        }

"\n" is the new line character. YOu read the file line-by-line, so that process strips the new line characters and gives you each line without a \n. So splitting on \n is pointless. Youwant to split each line into words, where words are separated by blanks, not newlines.
Look at line 20 - you are looping through all the characters in the first word. What you need is to loop through all the words, just looking at the first char of each.

(A small digression for anyone who has noticed that Java 8 is now released, so we have Lambdas and Streams to use for this problem. Here's a solution using current Java. Not useful for this OP I know, but a heads-up for everybody about the magnitude of the changes in Java 8. It takes a file path/name and returns the first letter of every word separated by commas)

    String firstLetters(String fileName) throws IOException {
        // get a reader for the file...
        BufferedReader br = Files.newBufferedReader(
                Paths.get(fileName), StandardCharsets.UTF_8);
        return  br.lines().  
                flatMap(line -> Stream.of(line.split("\\s+"))).
                map(word -> word.substring(0, 1)).
                collect(Collectors.joining(", "));
    }

i've never try coding using the current java before, but i've seen it once when i was searching on the google for this problem. may i know what does this ":" notation mean?

if split and get only the first char of the word is it like this?

while ((line = reader.readLine()) != null) {
            String[] name = line.split(" ");    
            //Fullname = name[0];
            for(int i = 0; i < name.length(); ++i){ 
                     Initials += Fullname.charAt(0);
            }

this is is the newest way i tried:

String ShortenedName = "";
        Scanner filescan = null;
        char NameAtFirst;

            filescan= new Scanner (new File("sample2.csv"));

            while (filescan.hasNext())
            {
                String line = "";
                String[] name = line.split(" ");
                String Name = filescan.next(); 
                ShortenedName +=  Name.charAt(0);   
                System.out.println(ShortenedName);

but the output that i got is:
W
WS
WSc
WScc
WSccd
WSccdC

is there anyway to fix it so that it become:

WS
cc
dC

thank you

well yes, you need to iterate a second time.
the first time over your file (which is what you are doing) by filescan.next() and filescan.hasNext()

the second time over the String that fileScan.next() returns.
it's from each of these Strings you need to run a split(" "); and use a println on the first letters of each word/name.

Your earlier version was almost there

    while ((line = reader.readLine()) != null) {
      String[] name = line.split(" ");
      //Fullname = name[0];
      for(int i = 0; i < name.length(); ++i){
        Initials += Fullname.charAt(0);
      }

It just needs you to use name[i] to refer to each name inside the inner loop, and you will be heading in hthe right direction...

       Initials += name[i].charAt(0);

ps Java 8 uses :: to refer to methods, eg this::doIt means "run the method doIt() for the current object", someObject::print means "run someObject's print() method". Used a lot to replace anonymous inner classes, eg for Runnables or Swing event listeners, eg

saveButton.addActionListener(this::save); 
// calls this object's save(ActionEvent e) when button clicked
while (filescan.hasNext())
            {
                String line = "";
                String[] name = line.split(" ");
                String Name = filescan.next(); 

                    for (int i =0; i <Name.length(); i++)
                    {       
                        String[] name2 = line.split(" ");
                        ShortenedName +=  Name.charAt(0);   
                    }

            }
            System.out.println(ShortenedName);

uhm, if i do this then i get: WWWWWWWSSSSSSSSSSSccccccccccccccdddddCCCCCCCCCCC

and if it's this:

while (filescan.hasNext())
            {
                String line = "";
                String[] name = line.split(" ");
                String Name = filescan.next(); 

                    for (int i =0; i <ShortenedName.length(); i++)
                    {       
                        String[] name2 = line.split(" ");

                    }
                ShortenedName +=  Name.charAt(0);   
            }
            System.out.println(ShortenedName);

then the output is : WSccdC

is it the way i do is wrong? i still couldn't get the output that i want

thank you

BufferedReader reader = null;
    String Fullname= "", Initials = "" ;
    String[] name;  
    try {

        File csvfile = new File ("sample3.csv");
        reader = new BufferedReader(new FileReader(csvfile));
        String line = "";   
        while ((line = reader.readLine()) != null) {
             name = line.split(" ");    
            //Fullname = name[i];
            for(int i = 0; i < name.length(); ++i){ 

                 Initials += name[i].charAt(0);
            }
            System.out.println(Initials);
        }

as for this one, i don't get why it gave me this error:

cannot find symbol: for(int i = 0; i < name.length(); ++i){
symbol:   method length()
location: variable name of type String[]
1 error

then i declared String[] name ="";
it gave empty output. is it wrong with this code?

That code is so nearly right!. It's just that for the length of an array you use myArray.length not myArray.length()
(yes, I know that's confusing - for a String it's length(), but for an array its just length)

Alternatively, make your code simpler by using an enhanced for/each loop, eg

String[] names = line.split(" "); 
for (String w : words) {
   initials += w.charAt(0);
   ...

thank you very much everyone! i figure out how to obtain this output:

WS
cc
dC

i reset the Initial = "" after System.out.println (Initial).

thank you very much for helping me to solve this problem :D

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.