How to write the contents of my array in a text file? - java

I have an array which has objects of people in a football team. It holds information such as their first name, second name and address. When i use the code shown below the text file contains values like this: member#29086037
The code is shown below:
try
{
PrintWriter pr = new PrintWriter ("memberDetails.txt");
for (int i = 0; i < collection.length; i++)
{
pr.println(collection[i]);
}
pr.close();
} catch (FileNotFoundException ex)
{
System.out.println(ex.getMessage());
System.out.println("in" + System.getProperty("user.dir"));
System.exit(1);
}
What am I doing wrong?

When you see that malarky with the numbers and class name like that, it means you haven't overriden your toString() method, so it defaults to Object.toString().
So, override the public String toString() method on your member class.

When you do pr.println(collection[i]); as you didn't override it, you print Object::toString which represents the object in this way by default:
The toString method for class Object returns a string consisting of the name of the class of which the object is an instance, the at-sign character `#', and the unsigned hexadecimal representation of the hash code of the object. In other words, this method returns a string equal to the value of:
getClass().getName() + '#' + Integer.toHexString(hashCode())
To print each field, use properties of the object, for example:
collection[i].getName();
collection[i].getAddress();
Other option, is to override toString() method of member.

You have to provide the path to the file correctly. I would suggest creating a file object and then pass it to Printwriter. This way you can also make sure if File exist before assigning it to printwriter.

As others have pointed out, assuming you have a class that models the players, you should provide a toString() implementation in the class. For example:
public class Player {
private String firstName;
private String lastName;
private String address;
...
#Override
public String toString() {
return String.format("Name: %s, %s. Address: %s", lastName, firstName, address);
}
}
After that's been done, it becomes trivial to write the player information into a file. Using an utility library such as Google's Guava, the solution simplifies into a one-liner:
Files.write(Joiner.on(StandardSystemProperty.LINE_SEPARATOR.value())
.join(collection),
new File("memberDetails.txt"),
Charsets.UTF_8);

Related

How do I get object and not address without using String/ toString?

I need to create my own String class called MyString without using default String class/vector API. I have to work on some required methods, and their return types are predetermined. I can add other methods as long as String is not used.
Expected use would be:
(at main) System.out.println(str.toLowerCase()) - returns lower case of str
When I want to work with toLowerCase() method with return type MyString, I can't return the object content but only return the address.
Normally, this problem would require modification of toString(), but since this method requires return type of String by default, I can't use modification of toString() for the assignment.
The assignment is supposed to be not so hard and should not require complex extensions. My constructor may be the problem, but I can't specify which part is.
Code
public class MyString {
private char value[];
MyString(char[] arr){
this.value = Arrays.copyOf(arr, arr.length);
}
...
MyString toLowerCase() { // can't change return type
for (int i =0; i<value.length; i++) {
if ((int)value[i] > 64 && (int)value[i] < 91) {
value[i] = (char) (value[i]+32);
}
}
return this; // this returns address, and I can't override toString
}
Problem with System.out.println(str.toLowerCase()) is it ends up calling PrintStream.println(Object o), but that method internally at some point calls o.toString() which uses code inherited from Object#toString() (since you couldn't override toString as it expect as result String which is forbidden in your project) which result in form TypeInfo#hexHashCode.
This means you can't use System.out.println(MyString).
BUT PrintStream (which instance is held by System.out) allows us to provide data to print in different forms. In this case you can use println(char[]). All you need to do is adding to MyString method like toCharArray() which would return (preferably a copy of) array of characters held by MyString class.
This way you can use it like System.out.println(myStringInstance.toCharArray()) so code from your main method would need to look like
System.out.println(str.toLowerCase().toCharArray());
// ^^^^^^^^^^^--this should return char[]
Firstly, the String class is an immutable type, i.e. the methods of String do not change the internal state (i.e. the char array), instead they return a new instance of type String.
To mirror that behavior you could implement something like this:
public MyString toLowerCase() {
char temp = new char[value.length];
// [...] Your code performing the actual logic on temp
return new MyString(temp);
}
The immutability (and its implications) of the String class is very important to understand in practice. For example, the following code procudes the intended result:
String word = "Word";
System.out.println("I can produce upper case (" + word.toUpperCase() + ") " +
"and lower case (" + word.toLowerCase() + ") " +
"without any side-effects on the original (" + word + ").");
However, it's not possible (without "hacky" solutions) to implement a method like this:
void shortenString(String inputAndOutput);
Second, the assignment expects that the class/method must be used as follows:
System.out.println(str.toLowerCase());
The attribute out is effectively a PrintStream, which offers (besides other methods) the following two:
println(Object x) - Prints an Object and then terminate the line.
println(String x) - Prints a String and then terminate the line.
If the method is called with an Object parameter, the internal implementation calls toString() on the given object, thus the only way to satisfy the requirement is to override this method. Unfortunately, this is not allowed by the assignment.
However, if it is not explicitly stated that the solution has to use java.lang.System, you could simply implement your own System class which accepts MyString, e.g.:
public class System {
public static class MyPrintStream /* optional: extends PrintStream */ {
public void println(MyString x) {
java.lang.System.out.println(x.getCharArray());
}
}
public static final out = new MyPrintStream();
}
This would allow you to use it exactly as described in the assignment:
import my.package.System;
public class Main {
public static void main(String[] args) {
// [...] Instantiate str
System.out.println(str.toLowerCase());
}
}

Android parse: Get strings from parsequeryadapter and store them into an ArrayList

I have a ParseQueryAdapter class, and my items are being retrieved successfully.
However, if I have this for loop to view the objects (strings):
for (int i =0;i<adapter.getCount();i++){
Log.d("Ab", adapter.getItem(i).toString());
}
I get these:
com.example.ab_me.example.classname#41ef11f8
com.example.ab_me.example.classname#41ef33d8
com.example.ab_me.example.classname#41ef40c0
Note: For security reasons, I replaced my app name with example and my classname with classname.
Why is this? It is supposed to be:
listItem1
listItem2
listItem3
Thanks in advance
The Object that is returned from getItem method call does not override toString() method, so java uses a default implementation in this case because it doesn't 'know' how to convert the object to a String type.
If you own this type, simply #Override the toString() method with your own implementation.
Example:
Assuming your type name is YourType. I mean, adapter.getItem(i) returns an object of YourType. In YourType.java:
class YourType {
private String exampleField1;
private String exampleField2;
#Override
public String toString() {
return exampleField1 + ", " + exampleField2;
}
}

Get Object from reference Id

is it possible to get an object from his reference id?
i get a list of String containing the reference id of an object like:
com.test.test.business.model.Gamma#20
how to get the object from this reference id?
it's only a string and it isn't castable to the object itself
What you see is called the default toString of an object. It is an amalgamation of the FQCN (fully qualified class name) of the class it belongs to and the hashCode of the object.
Quoting from the JavaDoc of toString:
The toString method for class Object returns a string consisting of
the name of the class of which the object is an instance, the at-sign
character `#', and the unsigned hexadecimal representation of the hash
code of the object. In other words, this method returns a string equal
to the value of:
getClass().getName() + '#' + Integer.toHexString(hashCode())
In short, you can't get an object using this reference id.
We can override toString to give a more human readable output. Take a look at the below two classes, with and without toString. Try to execute the main method and compare the output of the two print statements.
class Person {
private String name;
#Override
public String toString() {
return "Person [name=" + this.name + "]";
}
}
class Address {
private String town;
}
public class Test {
public static void main(String... args) {
Person person = new Person();
Address address = new Address();
System.out.println("Person is : " + person);
System.out.println("Address is : " + address);
}
}
However, if you are really looking for a way to persist objects and resurrect them at a later stage, you should read up on Serialization.

Java array, prints something else

I'm trying to print the items from my array, but when I run the program, it prints out Orders:testorder#4, testorder#5 and so on. Any tips on how I can fix it so it writes 123 Buy?
package hej;
public class TestOrder {
public static void main(String[] args) {
Order order1 = new Order("123", "Buy");
Order order2 = new Order("456", "Sell");
Order order3= new Order("231", "Buy");
Order order4= new Order("987", "Buy");
OrderRegister orderregister = new OrderRegister();
orderregister.addOrder(order1);
orderregister.addOrder(order2);
orderregister.addOrder(order3);
orderregister.addOrder(order4);
System.out.println("Orders: ");
for (int i = 0; i < orderregister.getArrayList().size(); i++){
System.out.println(orderregister.getArrayList().get(i) + "-");
}
}
}
Because you don't have a toString() method defined for your Order class.
When Java tries to print an Object, it attempts to call the toString() method for that Object, if it can't find one it uses the toString() from the Object superclass.
And the Object toString() by default does this:
getClass().getName() + '#' + Integer.toHexString(hashCode())
which is exactly what you are seeing as output.
Have TestOrder override the toString() method.
When you concatenate an object with a String (like in your System.out.println(...) statements), the toString() method is called on the object to convert it to a String first.
You need to override the toString() method on your Order class and have it generate the string form of the order.
This is exactly what you should expect, given that you haven't told Java any other way to convert an Order to a String. Override Order.toString() if you want Java to use some particular way of converting an Order to a String.
You could/should try overriding the toString() method(which is called implicitly in your example) as others have suggested.
For example:
#Override public String toString()
{
return String.format("%s , %s", this.getID(), this.getAction());
}

Custom 'String' Class

I'm trying to figure out how java classes work.
When I create a StringBuilder:
StringBuilder testString = new StringBuilder("Hello World!);
If I want to, say, get the value that testSting holds a reference to, I can simply call it like: System.out.println(testString);
This is cool behavior, but I'm unsure how to replicate it in classes that I make.
For instance, if I were to try and re-implement my own version of StringBuilder, the approach I would take (as a beginner), would be this:
class MyBuilder {
char[] string;
public MyBuilder(String s) {
string = new char[s.length()];
string = s.toCharArray();
}
So, to make the string an array I had to store it in a data field of the class. But then, to access this in my code, I can't print it by simply calling the variable name. I would have to use .property syntax. Thus, to duplicate the above example, I would have to type System.out.println(testString.value); Which isn't nearly as pretty.
How do you make a class such that it behaves like String or StringBuilder and returns its value without manually accessing the data fields?
Implement a toString method.
toString is a method on Object, so every java object inherits one. The default implementation that you inherit is only useful for getting the class type, and for distinguishing one object from another; the format is: ClassName#HashCode. There are no details unique to your implementation.
In your own classes, to get the description that you want you'll need to override the toString method, so that in contexts where a String is expected, e.g. when you call System.out.println(myObject.toString());, your own format is used.
It's often a good idea to do this, for a more readable description of your object. You can always call super.toString to include the output from the default - ClassName#HashCode - in your own output.
You can override Object.toString() in your object MyBuilder. System.out.println calls on this method for every object used. For example here, you could use:
#Override
public String toString() {
return Arrays.toString(string);
}
Overwrite the toString-Method
private String value;
public MyClass(String value) {
this.value = value;
}
public String toString() {
return value;
}

Categories