3

I have an assignment where we are required to create a User class with a toString() method. The toString method should return a string with all the information about the user. We are required to create an array of 50 User objects and print the information about each user on a separate line. The problem is, I want to keep everything in a neat table with all Strings of the same length. So for instance:

User Name          Password          Full Name                     Email
___________________________________________________________________________________________
shortUser          12345             John Smith                    jSmith@shortnames.com
thisUserIsLonger   1234567890        Smitty Werbenjagermanjensen   Smitty@thisOneIsLong.com

I would like to keep everything aligned as it is in the above table. This would be easy in C++ since I could just use setw() to dynamically pad spaces between according to the size of the field. Is something like this possible in Java?

4

2 に答える 2

2

これはあなたが探しているものと正確ではないかもしれませんが、printfとその兄弟に慣れている場合は、String.format()を見てください。

于 2012-09-03T03:53:28.423 に答える
0

There are many was to store the data and retrieve as you prefered eg : store in DBMS or serialize the data

As there is not much data I would stick to serialization.

  1. First you need to create person been class.

    class Person{
    String name;
    String pwd;
    String email;
    String fullName;
    
    // make the getters and setters
    
    }
    
  2. Set Person data using setters (you may use a loop)

  3. Add the object person to a ArrayList

    arrayListObj.add(person1);
    
  4. serialize the ArrayList

    try { System.out.println("serializing list"); FileOutputStream fout = new FileOutputStream("list.dat"); ObjectOutputStream oos = new ObjectOutputStream(fout); oos.writeObject(arrayListObj); oos.close(); } catch (Exception e) { e.printStackTrace(); }

  5. Deserialize as follows

     try {
         FileInputStream fin = new FileInputStream("list.dat");
         ObjectInputStream ois = new ObjectInputStream(fin);
         List<String> list = (ArrayList) ois.readObject();
    
         for (String s : list){
             System.out.println(s);
         }
    
         ois.close();
     }
     catch (Exception e) { 
         e.printStackTrace(); 
     }
    
  6. After deserializing you may have to use iterator to invoke the list

These are the basic steps that you could follow to achieve your target!

After words it is just about the print the result.

于 2012-09-03T04:18:28.393 に答える