简体   繁体   中英

How to start an interactive java app with gradle

I want to write a gradle task that runs me this small application:

import java.lang.IllegalArgumentException

class TestApp{
    companion object {
        @JvmStatic
        fun main(args:Array<String>){
            val a = try{
                args[0].toInt()
            }catch (e:Exception) {throw argException}

            val b = try{
                args[1].toInt()
            }catch (e:Exception) {throw argException}

            print("$a + $b = ")
            val answer = readLine()!!.toInt()

            println(if(a+b == answer)"CORRECT" else "WRONG!")
        }

        private val argException:IllegalArgumentException by lazy { IllegalArgumentException("expecting two integers as args") }
    }
}

If I run the application with, say, Intellij, the app will pause at the readline() and expect user input.

However, if I add a gradle task for it

task runTestApp(type:JavaExec){
    main = "${javaMainTestApp}"
    classpath = sourceSets.main.runtimeClasspath
}

and run, say,

gradle runTestApp --args="2 4"

Then I get

2 + 4 = Exception in thread "main" kotlin.KotlinNullPointerException
        at [...].app.TestApp$Companion.main(TestApp.kt:19)
        at [...].app.TestApp.main(TestApp.kt)

Why is that? And more importantly, how do I get the execution to wait for user input?

UPDATE

Thanks @tim_yates:

adding standardInput = System.in makes the app accept user input

but results in an output like:

3 + 5 =
<<==========---> 80% EXECUTING [20s]
> :runTestApp
8

where 8 is the user input.

consequently, when the app finishes, the output reads

3 + 5 =
<<======CORRECT> 80% EXECUTING [22s]

Maybe you could use the application plugin and do a gradle run . Or you could use the distribution plugin and run the script.

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