CommencerCommencer gratuitement

Convertir while en foreach

Auparavant, vous avez écrit une boucle while de style impératif pour trouver et afficher le nombre de points avant de « bust » pour cinq mains (une par joueur) dans une manche de Twenty-One :

// Define counter variable
var i = 0

// Create list with five hands of Twenty-One
var hands = List(16, 21, 8, 25, 4)

// Loop through hands
while(i < hands.length) {
  // Find and print number of points to bust
  println(pointsToBust(hands(i)))
  // Increment the counter variable
  i += 1
}

Dans cet exercice, vous allez convertir ce code vers un style plus fonctionnel, privilégié en Scala, en utilisant la méthode foreach. La fonction bust est déjà définie pour vous. Une version modifiée de pointsToBust (avec println) est fournie dans l’exemple de code.

Cet exercice fait partie du cours

Introduction à Scala

Afficher le cours

Instructions

  • Appelez la méthode foreach sur le tableau de tableaux hands, en parcourant chaque manche pour trouver le nombre de points avant bust à l’aide de la fonction pointsToBust.

Exercice interactif pratique

Essayez cet exercice en complétant cet exemple de code.

// Find the number of points that will cause a bust
def pointsToBust(hand: Int) = {
  // If the hand is a bust, 0 points remain
  if (bust(hand))
    println(0)
  // Otherwise, calculate the difference between 21 and the current hand
  else
    println(21 - hand)
}

// Create list with five hands of Twenty-One
var hands = List(16, 21, 8, 25, 4)

// Loop through hands, finding each hand's number of points to bust
___
Modifier et exécuter le code