In my program I\'m reading integers form console many times. Every time, I need to type this line.
new Scanner(System.in).nextInt();
I\'m
No. Java (the language) does not support macros of any sort.
However, certain constructs can be faked or wrapped. While the example is silly (why are you creating a new scanner each time!?!?!) the below shows how it can be achieved:
int nextInt() {
return new Scanner(System.in).nextInt();
}
...
int a = nextInt();
int b = nextInt();
But much better:
Scanner scanner = new Scanner(System.in);
int a = scanner.nextInt();
int b = scanner.nextInt();
Happy coding.
For comment:
Static methods can be called without needing an object to invoke them upon. However, in most cases one is already in an object. Consider:
public class Foo {
static int nextIntStatic() {
return 13;
}
int nextInt() {
return 42;
}
void realMain () {
// okay to call, same as this.nextInt()
// and we are "in" the object
int ni = nextInt();
}
public static void main(String[] args) {
// okay to call, is a static method
int nis = nextIntStatic();
Foo f = new Foo();
f.realMain();
}
}
Use a utility class and static import.
The utility class:
package my.utils;
public class ScannerUtils {
private ScannerUtils() {}
public static int readInt() {
return new Scanner(System.in).nextInt();
}
}
Using the utility class:
package my.examples;
import static my.utils.ScannerUtils.*;
class Example {
void foo() {
int i = readInt();
}
}
As others have said, you should probably cache your scanner, but that is a separate topic.