简体   繁体   中英

How can I print all content of an array in one line?

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

    Letter s = new Letter(); s.setCaracter("s");
    Letter e = new Letter(); e.setCaracter("e");
    Letter a = new Letter(); a.setCaracter("a");
    Letter r = new Letter(); r.setCaracter("r");
    Letter y = new Letter(); y.setCaracter("y");
    Letter o = new Letter(); o.setCaracter("o");
    Letter u = new Letter(); u.setCaracter("u");
    Letter n = new Letter(); n.setCaracter("n");
    Letter g = new Letter(); g.setCaracter("g"); 

    Letter name[] = new Letter[10];

    name[0] = s;
    name[1] = e;
    name[2] = a;
    name[3] = r;
    name[4] = s;
    name[5] = y;
    name[6] = o;
    name[7] = u;
    name[8] = n;
    name[9] = g;


    System.out.println(nombre[0].);//HERE!

  }
}

I would like to know a way to print in console all the array name[], with all of his content. To see something like this: searsyoung

I have tried with:

System.out.println(Arrays.toString(theArray));

it prints strange things ----> [Letter_Myname.Letter@1d5550d,...

Iterate the array.

for(Letter l : name){
 System.out.print(l);
}

In Letter implementation you have to override toString() like this

@Override
public String toString(){
   return caracter;
}

If you don't override toString you will get superclass toString implementation and then you have to do something tricky like this to get work but is not recommended .

 for(Letter l : name){
     System.out.print(l.getCaracter());
 }

I would suggest introducing another class Word to encapsulate things some more. The advantage this has over other approaches is that it would blend seamlessly if and when you extend your program to Sentence and Paragraph classes.

Letter[] name = new Letter[10];

// name[i] = ...

Word fname = new Word(name);
System.out.println(fname); // searsyoung

// Check the Letter class updates below
System.out.println(new Word(new Letter('J'), new Letter('o'),
                            new Letter('h'), new Letter('n'))); // John

Word Class

public class Word {

    private Letter[] letters;

    // makes use of var-args
    public Word(Letter... word) {
        this.letters = word;
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        for (Letter l : letters) {
            sb.append(l);
        }
        return sb.toString();
    }
}

Letter Class

public class Letter {

    private char c; // Prefer char over String

    public Letter(char c) {
        this.c = c;
    }

    public Letter() { // use new Letter('c') directly
    } // instead of two steps: new Letter(); setCaracter();

    public void setCaracter(char c) {
        this.c = c;
    }

    public char getCaracter() {
        return c;
    }

    @Override
    public String toString() {
        return Character.toString(c);
    }

}

Since, you've provided both Word#toString() as well as Letter#toString() implementations; you can simply print any Word without looping now. The looping still happens but the class takes upon itself to do it for you.

Three other solutions are possible in addition to foreach :

  • For Loop
  • Using an iterator
  • While Loop

Using for Loop:

 for (int i=0;i<name.length;i++)  System.out.print(name[i]);

In this case you need to define toString() in your Letter class or a getter getCaracter() that return the value or your caracter.

And then it become:

 for (int i=0;i<name.length;i++)  System.out.print(name[i].getCaracter());

Both toString() and getCaracter() return same variable your caracter but toString is prefered because it's called by default when you print an object.

An other way is to use an Iterator :

First we transform our name Array to arraylist:

ArrayList<Letter> listLetters = new ArrayList<Letter>( Arrays.asList(name) );

And then we iterate over it using iterator():

 Iterator itr = listLetters.iterator(); 

 while(itr.hasNext()) {

   Letter letter = itr.next(); 
   System.out.print(letter);

} 

Using While Loop:

 int i=0;
 while (i<name.length)  {    
     System.out.print(name[i].getCaracter());
     i++;  
  }

Using foreach Loop:

for(Letter letter : name){
 System.out.print(letter .getCaracter());
}

If you are using Java 8, you could do something like this:

Arrays.asList(name).forEach(System.out::print);

In case you did not override the toString() method, you could try this:

Arrays.asList(name).forEach(l -> System.out.print(l.getCaracter()));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM