File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Scala and the fly likes Guess a number? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Languages » Scala
Bookmark "Guess a number?" Watch "Guess a number?" New topic

Guess a number?

Klaus Jepsen

Joined: Oct 07, 2011
Posts: 1
I am making a program in scala where I need to guess a number between 1 and 100..

Need to look like this I have started on. But I need help getting further, and how to make this work..

Got following code for it now

object TestProgram extends App
var min = 1
var max = 100
var YesNo = readLine
val start = " "

println("Think of a number between 1 and 100. Press enter when ready")

println("Is the number 50? (y/n)")
println (YesNo)

if(YesNo == "y")
println ("I thought so")

while (YesNo == "n")
println ("Is it smaller or greater? (s/g)")

if(YesNo == "s")
max = max / 2

if(YesNo == "g")
min = 50
max = 100

What is wrong here, and what is needed to make this work ??

It need to ask i the terminal everytime, if the number is correct or smaller / greater ..
Garrett Rowe
Ranch Hand

Joined: Jan 17, 2006
Posts: 1296
When you say the program doesn't work. What it is currently doing wrong?

Some problems are so complex that you have to be highly intelligent and well informed just to be undecided about them. - Laurence J. Peter
Luigi Plinge
Ranch Hand

Joined: Jan 06, 2011
Posts: 441

Your main problem is that you're not reading a new value each time the player get the answer wrong. You need to re-assign the value of "YesNo" within the while loop with YesNo = readLine. At the start you can initialize it to null with var YesNo = _

Also you might find using pattern matching is neater than if-expressions. e.g.
Should you succeed, you next task is to re-write it without using any mutable state (i.e. no vars, only vals)...
I agree. Here's the link:
subject: Guess a number?
It's not a secret anymore!