简体   繁体   中英

Java Code Working On An Online Compiler But Not In Eclipse?

I am studying Computer Science at GCSE and I've came across a problem. Initially, our teacher cannot help me due to the AQA Guidelines but I am allowed to ask on forums etc. So here's the problem:

class Price {
    public static void main(String args[])  {
        Scanner keyboard = new Scanner (System.in);
        int day;
        double price = 0.00;



    System.out.print("How many days would you like to reserve the game?:  ");
    day = keyboard.nextInt();

    if (day >= 4 && day <= 5) {
        price = 5.55;

        System.out.print("You have chosen to reserve the game for " + day + " days! ");

        System.out.println("Please pay £" + price + ". " + " Enjoy your game!");
        }

    if (day == 3) {
        price = 3.45;

        System.out.print("You have chosen to reserve the game for " + day + " days! ");

        System.out.println("Please pay £" + price + ". " + " Enjoy your game!");
        }

    if (day >= 1 && day <= 2) {
        price = 2.75;

        System.out.print("You have chosen to reserve the game for " + day + " days! ");

        System.out.println("Please pay £" + price + ". " + " Enjoy your game!");

    }
    if (day > 5 || day <= 0) {
        System.out.println("Invalid Number - Days of Reservation Are 1-5 Only. Please Try Again.");
    }

    keyboard.close();
}
}

My problem is that this code works on Online Compilers such as www.browxy.com with no worries yet Eclipse reads the following error:

"Exception in thread "main" java.lang.Error: Unresolved compilation problems:

Scanner cannot be resolved to a type

Scanner cannot be resolved to a type

at Price.main(Price.java:3)"

Has anyone got a solution?

Thanks :)

You have to add an import statement for the Scanner class before the class definition:

import java.util.Scanner;

Most likely the classes from the java.util package are imported by default in the online IDE.

Also, Eclipse (and most of the other IDEs, actually) support a keyboard shortcut, which adds the import statements for you. Press Ctrl + Shift + O and you're done.

you should import Scanner class in java to have capability of compiler to accept user input on runtime add below line on top of your class declaration and the problem will get solved

import java.util.Scanner;

Note: you can also use compile time arguments like for example args[] if scanner class is not present in your JDK version

Scanner is present from java 1.5. Check if you jdk is a version prior to 1.5. If your jdk version is 1.5 or later you need to add the import java.util.Scanner at the top of the file.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM