2017-03-16 44 views
0

我想編寫一個程序,可以使用Scala找到二次方程的根。輸入應該是一個二進制方程,形式爲ax^2 + bx + c(例如:5x^2 + 2x + 3)作爲一個字符串。在Scala中輸入爲二進制表達式的提取係數

我設法對根的計算進行編碼,但無法從輸入中提取係數。下面是我寫的用於提取係數到目前爲止的代碼:如果輸入不只是拋出一個錯誤與正則表達式

def getCoef(poly: String) = { 
    var aT: String = "" 
    var bT: String = "" 
    var cT: String = "" 
    var x: Int = 2 
    for (i <- poly.length - 1 to 0) { 
    val t: String = poly(i).toString 
    if (x == 2) { 
     if (t forall Character.isDigit) aT = aT + t(i) 
     else if (t == "^") {i = i + 1; x = 1} 
    } 
    else if (x == 1) { 
     if (t forall Character.isDigit) bT = bT + t(i) 
     else if (t == "+" || t == "-") x = 0 
    } 
    else if (x == 0) { 
     if (t forall Character.isDigit) cT = cT + t(i) 
    } 
    val a: Int = aT.toInt 
    val b: Int = bT.toInt 
    val c: Int = cT.toInt 
    (a, b, c) 
    } 
} 
+0

你有沒有想過使用正則表達式?不知道你的輸入字符串有多複雜,但是你的問題是解析,並且有很好的解決方案,比如正則表達式或者Scala解析器組合器。 – stholzm

+0

str.split('x')。map(v => v.replace(「^ 2」,「」))。map(_。toDouble) – FatTail

+0

如果你對正則表達式不太熱衷,並且你的輸入與你一樣描述。 – FatTail

回答

0

簡單的解決方案:(減去EG)

def getCoef(poly: String) = { 
    val polyPattern = """(\d+)x\^2\+(\d+)x\+(\d+)""".r 
    val matcher = polyPattern.findFirstMatchIn(poly).get 
    (matcher.group(1).toInt, matcher.group(2).toInt, matcher.group(3).toInt) 
} 

無法處理所有的情況下不符合該模式,但它應該讓你去。