• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Guess a number?

 
Klaus Jepsen
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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(start)

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)")
println(YesNo)

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
Posts: 1296
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
When you say the program doesn't work. What it is currently doing wrong?
 
Luigi Plinge
Ranch Hand
Posts: 441
IntelliJ IDE Scala Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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)...
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic