PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, September 16, 2022

[FIXED] How to print the output of an accessor of every instance of a class?

 September 16, 2022     arrays, class, foreach, java, printing     No comments   

Issue

How would you go about creating a class like this:

public class tmUser {
    
    private String Username;
    private int wHours;
    static int numUsers;
    
    
    public tmUser(){
        Username = "";
        wHours = 0;
    }
    
    public tmUser(String U, int H){
        Username = U;
        wHours = H;
    }
    
    public void setUsername(String U){
        Username = U;
    }
    
    public void setwHours(int H){
        wHours = H;
    }
    
    public String getUsername(){
        return Username;
    }
    
    public int getwHours(){
        return wHours;
    }
    
    public static void initnumUsers(){
        numUsers = 0;
    }
    
    public static int getnumUsers(){
        return numUsers;
    }
}

and then printing all of tmUser instances Username variable? in maybe a for each loop? I'm hoping for something like:

for each(tmUser){
    System.out.println(Username);
}

This is for a menu in a program which displays all created users usernames.


Solution

You almost had it:

List<TmUser> tmUsers = ... 
for(TmUser user : tmUsers) {
    System.out.println(user.getUsername());
}

You would also want to capitalize tmUser into TmUser.



Answered By - Johan Sjöberg
Answer Checked By - Pedro (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing