String n = reader.toString();
- this line is causing a problem.
Method .toString()
isn't provided to help you get an input from Scanner
. Instead of that, you should have used String n = reader.nextLine()
- it reads a single line from input given with the standard input device (I guess it's a keyboard in your example) or from another specified device.
Method .toString()
is provided to give you another possibilities. This is what Java API documentation says about it:
" .toString() returns a string representation of the object. In general, the toString method returns a string that "textually represents" this object. The result should be a concise but informative representation that is easy for a person to read. It is recommended that all subclasses override this method."
Every class created in Java extends class Object (which contains method toString()
). So for instances of objects created by yourself there is a possibility to invoke a method toString(). Sometimes you might not be satisfied with the informations given to you with that method (by default you often get only the address in memory where the refence of specific object points to), so you can simply override this method in your class. There is a simple example how you can achieve that to make it print for you more helpful informations:
class MyClass {
Integer i = 55;
public String toString() {
return "i stored in MyClass: " + i;
}
}
public class Test {
public static void main(String[ ] args) {
MyClass obj = new MyClass();
System.out.println(obj);
}
}
// That code gives a following output:
// i stored in MyClass: 55