-4

I am new to Java and want to work on some stuff over the summer before I start classes. I want to open a plain text file using Intellji as my java environment.

The text file says "stay lifted".

What keeps happening is when I hit RUN it displayed "null".

import java.util.Scanner;
public class BonjourWorld {
private static Object Scanner;

public static void main(String[]args){
    Scanner res = new Scanner("staylifted.txt");
        System.out.println(Scanner);
    }
}
  • Possible duplicate of https://stackoverflow.com/questions/2049380/reading-a-text-file-in-java – devgianlu Apr 24 '19 at 16:04
  • 2
    Possible duplicate of [Reading a .txt file using Scanner class in Java](https://stackoverflow.com/questions/13185727/reading-a-txt-file-using-scanner-class-in-java) – Mike G Apr 24 '19 at 16:06
  • 1
    Default value for any `Object` reference in Java is `null`. This includes the `Scanner` field of your `BonjourWorld` class that you print. If you print `null`, it will indeed print `"null"`. – M. Prokhorov Apr 24 '19 at 16:07
  • It helps to stick to the Java naming conventions here - `camelCase` for variables and `TitleCase` for class names, makes it easier for you to see what you're actually printing – JonK Apr 24 '19 at 16:07
  • This shouldn't even compile. – NeplatnyUdaj Apr 24 '19 at 16:25

1 Answers1

0

the null is happening because you are printing a null object named 'Scanner' that is not the object you want to print, that is 'res'.

You may want to read the Scanner api https://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html because just printing the 'res' object will not return what you want.

Also, look for usage examples of the Scanner class

ViBort
  • 26
  • 3