Do I kneed to import libraries for different files? - java

Say I have two files:
// File Main.java
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// Scanner stuff here...
Food.fries();
}
}
// File Food.java
public class Food {
public static void fries() {
System.out.println("Some fries...")
// Can I do Scanner stuff here without importing?
}
}
I know that if classes are in the same file, I don't need to import for each class. Now, if I wanted to do operations with Scanner in class Food (separate file), do I need to import Scanner again?

You can import the Scanner class again to be able to use it inside Food class.
But, what I recommend it's you make sc variable as static and global (Scanner sc = new Scanner(System.in);)
So, in your main class you will have to create the variable like:
public class Main {
public static Scanner sc = new Scanner(System.in);
public static void main(String[] args) {
// Scanner stuff here...
Food.fries();
}
}
And inside your Food class:
public static void fries() {
System.out.println("Some fries...Give me a number:");
Main.sc.nextInt();
}
Those examples work if you have the files in the same package.
Now, you have to be careful here, Because if you have your Main class in another java package (or folder), then, you will have to import the Main class or you can use a static import. You can use that to avoid the use of the syntax Classname.your_static_method(). For example, your Main class:
import java.util.Scanner;
import static yourpackagename.Food.fries;
public class Main {
public static Scanner sc = new Scanner(System.in);
public static void main(String[] args) {
// Scanner stuff here...
fries();
}
}
As you can see now, I used a static import to use the fries() method which you have in the another class. So inside the main, you can call the method with the simple name, and not using the syntax Classname.static_method()
And inside Food class, you can do the same with Scanner object (sc):
import static yourpackagename.Main.sc;
public class Food {
public static void fries() {
System.out.println("Some fries...Give me a number:")
sc.nextInt();
}
}
Those examples work for files in the same package or in separate ones. You only have to do the import correctly.
Now, if you don't want to use a static import and the files or classes are in separate packages, you will have to import the class as always and use the syntax: Classname.static_methodorvariable()
import java.util.Scanner;
import thepackgename.Food;
public class Main {
public static Scanner sc = new Scanner(System.in);
public static void main(String[] args) {
// Scanner stuff here...
Food.fries();
}
}
Food class:
import thepackagename.Main;
public class Food {
public static void fries() {
System.out.println("Some fries...Give me a number:")
Main.sc.nextInt();
}
}

Related

using a static method in a different class

Let us suppose we have a class:
package package1;
public class Car {
public static int brake()
{
int x;
//some functionalities
}
//other functionalities
}
I want to ask for using this method brake in classes of different package, do we need to include package name also? -- int xyz=package1.Car.brake(); or simply Car.brake(); will work
You can import package or use full path of method:
First solution:
public class App {
public static void main(String[] args) {
package1.Car.brake();
}
}
Second solution:
import package1.Car;
public class App {
public static void main(String[] args) {
Car.brake();
}
}
Add import statement like import package1.Car; and then you can use Car.brake(); to call the function. Read more about imports here

Please, can you tell me the reason why we declare a scanner class object the second time if we want to use it in a method outside the main method?

For example:
static void lod(){
Scanner j = new Scanner(System.in);
String m = j.next();
}
public static void main(String[] args) {
Scanner j = new Scanner(System.in);
String val = j.next();
}
}
Like, why should I declare the Scanner class object again in the method lod before accessing the scanner class in the method Los.
... why we declare a scanner class object the second time if we want
to use it in a method outside the main method?
You do not have to do it and it is also not a clean way to do it. I would use one of the following ways:
Declare the Scanner object as an instance variable. However, you won't be able to use it directly inside a static method (including main) as you can't access a non-static member inside a static method directly. In a static method, you will be able to access an instance variable only through the instance of the class e.g.
import java.util.Scanner;
public class MyClass {
Scanner scanner = new Scanner(System.in);
public static void main(String[] args) {
MyClass obj = new MyClass();
System.out.print("Enter a word: ");
System.out.println(obj.scanner.nextLine());
}
static void lod() {
MyClass obj = new MyClass();
String m = obj.scanner.next();
}
}
Declare the Scanner object as a class variable (i.e. static variable at class level) e.g.
import java.util.Scanner;
public class MyClass {
static Scanner scanner = new Scanner(System.in);
public static void main(String[] args) {
System.out.print("Enter a word: ");
System.out.println(scanner.nextLine());
}
static void lod() {
String m = scanner.next();
}
}
Pass the Scanner object to the methods being called from main e.g.
import java.util.Scanner;
public class MyClass {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a word: ");
System.out.println(scanner.nextLine());
}
static void lod(Scanner scanner) {
String m = scanner.next();
}
}
You don't need to!
You can declare Scanner object at the class level like this,
class Test {
static Scanner j = new Scanner(System.in);
....
}
In Java the objects can be created inside methodsor outside and so they are only for that method or for the whole class but I don't recomend you to do that becouse every time the class is used the method is created even though you're accesing a method that don't uses it. Instead, you can declarate it outside the method and it will be accessible for all the methods from the class, but it will have to be created separately inside every method and they will be destroyed in the end of the method. Example:
class example{
Canstructor name;
public void method1(){
name = new Constructor();
}
public void method2(){
name = new Constructor();
}
}

Errors when trying to use import java.util.Scanner

I'm new to coding and I'm going through an online course (MOOC). I'm on a section about reading user input and I copy-pasted the code from the website into Netbeans but I'm getting errors like illegal start of expression and not a statement. Here's my code:
public class JavaApplication2 {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
import java.util.Scanner;
public class ProgramName {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
// code here
}
}
}
}
I get illegal start of expression for the import and public class lines. I also get a not a statement error for the import line. Lastly I get illegal static declaration for the public static void line.
Any help would be appreciated. Thanks!
The import goes here:
import java.util.Scanner;
public class JavaApplication2 {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
// code here
}
}
It is not a property of the class but a reference the compiler needs to be able to tell what "Scanner" (in this context) refers to. In this case it states that Scanner is defined in java.util which is part of the Java Runtime Environment (JRE).
Furthermore as you go on coding you should structure your files into folders.
As soon as you do so you will have to add this type of line in the first line of the file: package folderName.folderName0.
If you want to use one of your classes from another one you will have to add an import like: import folderName.folderName0.JavaApplication2
You've put an entire java source file into a main function. Simply do this instead:
import java.util.Scanner;
public class JavaApplication2 {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
}
}
You cannot put import and package statements inside a class. They should be done before class definitions.
Try this code:-
import java.util.Scanner;
// import before class definition.
public class JavaApplication2 {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
public class ProgramName {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
// code here
}
}
}
}
Type this in the header of the page : import java.util.Scanner;
you missing import important : import java.util.Scanner;
Exmple :
import java.util.Scanner;
public class JavaApplication2 {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
import java.util.Scanner;
public class ProgramName {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
// code here
}
}
}
}

How do I use the Rectangle object [duplicate]

When i want import scanner class in my project eclipse show me some errore :
Exception in thread "main" java.lang.Error: Unresolved compilation problems:
The constructor Scanner(InputStream) is undefined
The method nextLine() is undefined for the type Scanner
and this is my code :
import java.util.Scanner;
public class Scanner {
public static void main(String[] args) {
Scanner myScanner = new Scanner(System.in);
System.out.println(myScanner.nextLine());
}
}
The problem is that you're also declaring a class called Scanner. That means that when you then declare a variable of type Scanner and try to call the constructor, the compiler thinks you're talking about your class. Just change your own class to something else (e.g. Test):
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner myScanner = new Scanner(System.in);
System.out.println(myScanner.nextLine());
}
}
Alternatively you could just fully-qualify the name when you mean java.util.Scanner - but this would be a bad idea in terms of readability.
// Please don't do this - but it would work.
public class Scanner {
public static void main(String[] args) {
java.util.Scanner myScanner = new java.util.Scanner(System.in);
System.out.println(myScanner.nextLine());
}
}
Try
java.util.Scanner myScanner = new java.util.Scanner(System.in);
instead. Else the compiler tries to instantiate your class which is also called Scanner. Or just rename your own Scanner class to something else.
Try to change your class name eg:
import java.util.Scanner;
public class ScannerTest {
public static void main(String[] args) {
Scanner myScanner = new Scanner(System.in);
System.out.println(myScanner.nextLine());
}
}
Please change the name of your class:
public class Scanner {
to some other name. The compiler is unable to see Scanner as java.util.Scanner because it sees it as your class (which doesn't have such constructor nor method so it gives you errors informing about it).
You should give class name as different then API classes of Java.So just change class name from Scanner to ScannerProgram.
import java.util.Scanner;
public class ScannerProgram {
public static void main(String[] args) {
Scanner myScanner = new Scanner(System.in);
System.out.println(myScanner.nextLine());
}
}

Why won't Eclipse find my main class

Why won't my program find my main class? I don't think you need the rest of the parse() function to understand what is wrong... let me know
package help;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
public class help {
ArrayList<Character> StringList = new ArrayList<Character>();
static char[] data;
String val;
public void main(String[] args){
InputStreamReader ISR = new InputStreamReader (System.in);
BufferedReader BR = new BufferedReader(ISR);
try{
int sCurrentChar;
while ((sCurrentChar = BR.read()) != -1) {
parse((char) sCurrentChar);
}
} catch(IOException e){
e.printStackTrace();
}
}
public void parse(char x){
boolean done =false;
int state =0;
The main() method needs to be static:
public static void main(String[] args) {
...
}
For further information, read Why is the Java main method static?.
Also, I would recommend you to follow Java naming conventions. Member names of the form someMember, and class names of the form SomeClass.
The correct way to declare main method is :
public static void main(String args[]){
........
}
Yes because signature of the main method requires static.
public static void main(String args[])
Only at this point the JVM will recognize the main method as the entry point of the program and will execute.
You will need to have parse method to be static if you want in the same class.
Or else you can use a separate class for parsing..
You need to have a
public static void main(String [] args){
rather than
public void main(String [] args){
You don't have it as static

Categories