我想在程序中实现命令行,以便它们可以是可选的,但到目前为止,我可以运行程序的唯一方法是在命令行中运行程序时输入3个参数。有什么方法可以让我只输入一个参数的最小值,而另两个参数是可选的吗?
这是我的代码的开头:
import scala.collection.mutable.ListBuffer
import util.control.Breaks._
object part3 {
var newStartTime = 0
var newEndTime = 0
var csvStartTime = 0
var csvEndTime = 0
def main(args: Array[String]): Unit = {
var csV = args(0)
var daY = args(1)
var time1 = args(2)
var time2 = args(3)
newEndTime = checkLengths(time1, time2)
val bufferedSource = io.Source.fromFile(csV)
var z = new ListBuffer[String]()
var z2 = new ListBuffer[String]()
var i = 0
更新的代码:
val fileName = args(0)
courseCode1 = args(1)
val courseCode2: Option[String] = Try(args(2)).toOption
val courseCode3: Option[String] = Try(args(3)).toOption
val extraCourseSelection = for {
c2 <- courseCode2
c3 <- courseCode3
}
courseCodeFixed1 = courseCode1.toUpperCase.patch(4, " ", 0)
if(c2!=null)
{
courseCodeFixed2 = c2.toUpperCase.patch(4, " ", 0)
}
if(c3!=null)
{
courseCodeFixed3 = c3.toUpperCase.patch(4, " ", 0)
}
print(courseCodeFixed2)
print(courseCodeFixed3)
我尝试实现此解决方案,但现在它根本不想读取任何命令行参数
答案 0 :(得分:1)
您可以使用scala.util.Try
来捕获索引超出范围的异常,并使用toOption
将Try[_]
转换为Option[_]
:
import scala.util.Try
...
val csV: Option[String] = Try(args(0)).toOption
val daY: Option[String] = Try(args(1)).toOption
val time1: Option[String] = Try(args(2)).toOption
val time2: Option[String] = Try(args(3)).toOption
然后使用可选的值,您可以将其用于理解:
val newEndTime = for {
t1 <- time1
t2 <- time2
} yield checkLengths(t1, t2)
答案 1 :(得分:1)
val fileName = args(0)
val courseCode1 = args(1).toUpperCase.patch(4, " ", 0)
val courseCode2 = args.lift(2).map(_.toUpperCase.patch(4, " ", 0))
val courseCode3 = args.lift(3).map(_.toUpperCase.patch(4, " ", 0))
如果您不希望获得.getOrElse()
结果,则可以添加Option[String]
以提供默认值。