// // program to track bank balance and transactions // filename must be given as command-line argument // file will contain: // line with ending balance // lines containing transactions (amount followed by description), // in reverse order (newest first) // program then prompts repeatedly for one of the following: // 't' for transaction -- amount (positive for credit, negative for debit) // and description // 'h' for transaction history // 'q' to quit // // on exit, write initial balance and transactions back to file if (args.length < 1) { println("must give filename as argument") sys.exit(1) } val filename = args(0) var (balance, history) = readFile(filename) var choice = ' ' do { println("current balance $" + balance) println("what do you want to do?") println("(t for transaction, h for history, q for quit)") choice = readChar choice match { case 't' => println("enter amount (integer, positive for credit, negative for debit)") val amt = readInt println("enter description (line of text)") val text = readLine history = (amt, text) :: history balance += amt case 'h' => for (trans <- history) { println(trans) // FIXME format this better } case 'q' => println("ending balance $" + balance) writeFile(filename, balance, history) case _ => println("invalid choice") } } while (choice != 'q') // returns (balance, history) def readFile(filename : String) : (Int, List[(Int,String)]) = { val source = scala.io.Source.fromFile(filename) val lines = source.getLines val bal = lines.next.toInt val hist = lines.toList.map(line => { val firstBlank = line.indexOf(' ') val amt = line.substring(0, firstBlank).toInt val text = line.substring(firstBlank+1) (amt, text) }) // ANOTHER WAY //var hist = List[(Int,String)]() //for (line <- lines) { // val firstBlank = line.indexOf(' ') // val amt = line.substring(0, firstBlank) // val text = line.substring(firstBlank+1) // hist = (amt.toInt, text) :: hist source.close (bal, hist) } def writeFile(filename : String, bal : Int, hist : List[(Int,String)]) { val pw = new java.io.PrintWriter(new java.io.File(filename)) pw.println(bal) for (trans <- hist) { val (a,t) = trans pw.println(a + " " + t) } pw.close }