How to make System.out.println() shorter

后端 未结 12 884
伪装坚强ぢ
伪装坚强ぢ 2020-12-04 07:10

Please advice on where can I find the lib in order to use the shorter expression of System.out.println() and where should I place that lib.

相关标签:
12条回答
  • 2020-12-04 07:36

    As Bakkal explained, for the keyboard shortcuts, in netbeans you can go to tools->options->editor->code templates and add or edit your own shortcuts.

    In Eclipse it's on templates.

    0 讨论(0)
  • 2020-12-04 07:37

    Java is a verbose language.

    If you are only 3 days in, and this is already bothering you, maybe you'd be better off learning a different language like Scala:

    scala> println("Hello World")
    Hello World
    

    In a loose sense, this would qualify as using a "library" to enable shorter expressions ;)

    0 讨论(0)
  • 2020-12-04 07:39

    Logging libraries

    You could use logging libraries instead of re-inventing the wheel. Log4j for instance will provide methods for different messages like info(), warn() and error().

    Homemade methods

    or simply make a println method of your own and call it:

    void println(Object line) {
        System.out.println(line);
    }
    
    println("Hello World");
    

    IDE keyboard shortcuts

    IntelliJ IDEA and NetBeans:

    you type sout then press TAB, and it types System.out.println() for you, with the cursor in the right place.

    Eclipse:

    Type syso then press CTRL + SPACE.

    Other

    Find a "snippets" plugin for your favorite text editor/IDE

    Static Import

    import static java.lang.System.out;
    
    out.println("Hello World");
    

    Explore JVM languages

    Scala

    println("Hello, World!")
    

    Groovy

    println "Hello, World!" 
    

    Jython

    print "Hello, World!" 
    

    JRuby

    puts "Hello, World!" 
    

    Clojure

    (println "Hello, World!")
    

    Rhino

    print('Hello, World!'); 
    
    0 讨论(0)
  • 2020-12-04 07:44

    Use log4j or JDK logging so you can just create a static logger in the class and call it like this:

    LOG.info("foo")
    
    0 讨论(0)
  • 2020-12-04 07:49

    Some interesting alternatives:

    OPTION 1

    PrintStream p = System.out;
    p.println("hello");
    

    OPTION 2

    PrintWriter p = new PrintWriter(System.out, true);
    p.println("Hello");
    
    0 讨论(0)
  • 2020-12-04 07:50

    My solution for BlueJ is to edit the New Class template "stdclass.tmpl" in Program Files (x86)\BlueJ\lib\english\templates\newclass and add this method:

    public static <T> void p(T s)
    {
        System.out.println(s);
    }
    

    Or this other version:

    public static void p(Object s)
    {
        System.out.println(s);
    }
    

    As for Eclipse I'm using the suggested shortcut syso + <Ctrl> + <Space> :)

    0 讨论(0)
提交回复
热议问题