0

So I've made a 'friends' class in Java, each friend having a: Name, Birthday, Nickname, Type. I don't know how to print out all of this data per each friend in the class, and that is my goal. I want to be able to have something like this:

for(//each person in my friends class, print out the data)

and the have it look something like this:

System.out.println("Name: " + Friend.name);
System.out.println("Bday: " + Friend.birthday);
System.out.println("Nickname: " + Friend.nickname);
System.out.println("Type: " + Friend.type);

and the output would be something like:

Name: Spencer
Bday: 101002
Nickname: Colin
Type: Tier 1

Here's what I have so far:

import java.util.Random;

class friends {
    String name;
    int birthday;
    String nickname;
    String type;
}

public class RipStefan {
    public static void main(String[] args) {
        friends Colin = new friends();
        Colin.name = "Spencer";
        Colin.birthday = 101002;
        Colin.nickname = "Colin";
        Colin.type = "Tier 1";

    friends Sanger = new friends();
    Sanger.name = "Oliver";
    Sanger.birthday = 112702;
    Sanger.nickname = "Sanger";
    Sanger.type = "Tier 1";

    friends Paul = new friends();
    Paul.name = "Paul";
    Paul.birthday = 022103;
    Paul.nickname = "PBJ";
    Paul.type = "Tier 1";



    }
}

Sorry if any of the formatting is off, this is my first question on Stack Overflow.

  • 1
    The simple answer: dont fetch values individually, instead have your class implement/override the toString() method. – GhostCat Aug 28 '18 at 13:10
  • By convention Java classes should start with a capital letter, also I think you should lose the 's' because the class represents one friend. `friends -> Friend` – xtratic Aug 28 '18 at 13:14
  • 1
    @GhostCat Wrong duplicate. – Murat Karagöz Aug 28 '18 at 13:17
  • @MuratK. I added another one. – GhostCat Aug 28 '18 at 13:20
  • Look at Apache Commons' ReflectionToStringBuilder, which greatly helps to build dynamic toString representation: https://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/builder/ReflectionToStringBuilder.html – spi Aug 28 '18 at 13:32

1 Answers1

3

You need a collection in order to be able to iterate over the elements. Right now you instantiate Friend objects without collection them. You could use a List e.g.

List<Friends> listOfFriends = new ArrayList<>();
listOfFriends.add(colin);
listOfFriends.add(sanger);
listOfFriends.add(paul);

and then you could do

for(Friends f : listOfFriends){
 // print out stuff for every friend from the variable f
}

You should also stick to the naming conventions. Friends class should be Friend and so on.

Murat Karagöz
  • 35,401
  • 16
  • 78
  • 107