0

I'm trying to read the line given by the user and take it and print out the right thing. Right now, when I enter Julian, it doesn't print anything.

import java.util.Scanner;

public class fantasyFootball {

    public static void main(String[ ] args) {
        Scanner reader = new Scanner(System.in); 
        System.out.println("Enter a name: ");
        String n = reader.toString();

        if("Julian".equals(n)){ 
            System.out.println("Win and Win: You go to the Playoffs");
            System.out.println("Lose and Win: ");
            System.out.println("Lose and Win: ");
            System.out.println("Lose and Lose: ");
        }
        reader.close();
    } 
}
Mureinik
  • 297,002
  • 52
  • 306
  • 350
Mark
  • 31
  • 1
  • 5

2 Answers2

4

Using toString() doesn't get any input from the Scanner. You probably meant to use something like this:

String n = reader.nextLine();
Mureinik
  • 297,002
  • 52
  • 306
  • 350
0

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
Przemysław Moskal
  • 3,551
  • 2
  • 12
  • 21