問題描述
在我的程序中,我多次從控制臺讀取整數.每次,我都需要輸入這一行.
In my program I'm reading integers form console many times. Every time, I need to type this line.
new Scanner(System.in).nextInt();
我習慣了 C/C++,我想知道我是否可以定義類似的東西
I'm used to C/C++ and I'm wondering if I can define something like
#define READINT Scanner(System.in).nextInt();
然后,在我的 java 程序的每個地方,我都可以將表單控制臺讀取為
and then, in every place in my java program I can read form console as
int a = new READINT;
但是我閱讀了表格書籍 Java 不支持宏.
But I read form books Java does not support macros.
請有人解釋一下為什么會這樣,我可以用其他方式嗎?
Someone please explain me why is it so, and can I do this in any other way.
推薦答案
你可以但你不應該.
您不應該因為以這種方式使用預處理器 被認為是不好的做法,并且有更好、更符合 Java 習慣的方法來解決這個用例.
You shouldn't because using the pre-processor in that way is considered bad practice to start with, and there are better and more Java-idiomatic ways to solve this use case.
Java 本身不支持宏.另一方面,您可以通過 C 預處理器 管道源代碼a>(簡稱CPP)就像C/C++編譯鏈一樣.
Java itself doesn't support macros. On the other hand, you could pipe the source code through the C pre processor (CPP for short) just like the C/C++ compile chain does.
這是一個演示:
src/Test.java
:
#define READINT (new java.util.Scanner(System.in).nextInt())
class Test {
public static void main(String[] args) {
int i = READINT;
}
}
cpp
命令:
cpp
command:
$ cpp -P src/Test.java preprocessed/Test.java
結果:
class Test {
public static void main(String[] args) {
int i = (new java.util.Scanner(System.in).nextInt());
}
}
編譯:
$ javac preprocessed/Test.java
您可以使用靜態方法編寫自己的實用程序類:
You can write your own utility class with a static method instead:
import java.util.Scanner;
class StdinUtil {
public final static Scanner STDIN = new Scanner(System.in);
public static int readInt() {
return STDIN.nextInt();
}
}
而當你想使用它的時候,你可以靜態導入readInt
方法:
And when you want to use it, you can statically import the readInt
method:
import static StdinUtil.readInt;
class Test {
public static void main(String[] args) {
int i = readInt();
}
}
(或執行 static import StdinUtil.STDIN;
并使用 STDIN.nextInt()
.)
(or do static import StdinUtil.STDIN;
and use STDIN.nextInt()
.)
我自己曾經對 Java 代碼使用過 CPP 預處理方法!我正在為一門課程創建一個編程作業.我希望能夠輕松地從參考解決方案中提取代碼骨架.所以我只是使用了幾個 #ifdef
來過濾掉解決方案的秘密"部分.這樣我就可以維護參考解決方案,并輕松地重新生成代碼骨架.
I myself used the CPP preprocessing approach on Java code once! I was creating a programming assignment for a course. I wanted to be able to easily extract a code skeleton out of the reference solution. So I just used a few #ifdef
s to filter out the "secret" parts of the solution. That way I could maintain the reference solution, and easily regenerate the code skeleton.
這篇文章已被重寫為一篇文章這里.
This post has been rewritten as an article here.
(*) 因為我討厭用你不應該"來回答問題.此外,一些未來的讀者可能有充分的理由希望將 cpp
與 Java 源代碼結合使用!
(*) Since I hate answering questions with "you shouldn't". Besides, some future reader may have good reasons for wanting to use the cpp
in conjunction with Java sources!
這篇關于我可以在 Java 源文件中有宏嗎的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!