• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Guess a number?

 
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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 ..
 
Ranch Hand
Posts: 1296
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
When you say the program doesn't work. What it is currently doing wrong?
 
Ranch Hand
Posts: 441
Scala IntelliJ IDE Windows
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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)...
 
reply
    Bookmark Topic Watch Topic
  • New Topic