Search code examples
javascriptloopsif-statementdo-whilecancellation

Javascript if statement cancels while loop?



I am currently working on some code, in which i tried to programm a very weak KI. I have done this with an endless while loop with prompts and if statements. But after the first if statement i couldn't add anymore ifs without, that the loop wouldn't work anymore. I tried many thing but nothing seems to work. I hope you can help me...

var b = 1;
var antwort;
do {
  input = prompt(antwort);

  var eingabe = input.toLowerCase();

  var x = Math.round(Math.random() * (6 - 1)) + 1;

  if (eingabe === "hallo" || eingabe === "hi") {
    switch (x) {

      case 1:
        {
          antwort = "Hallo!";
          break;
        }

      case 2:
        {
          antwort = "Na, wie geht es dir?";
          break;
        }

      case 3:
        {
          antwort = "Guten Tag!";
          break;
        }

      case 4:
        {
          antwort = "Hi.";
          break;
        }

      case 5:
        {
          antwort = eingabe + ".";
          break;
        }
    }
  } else if (eingabe.includes("gut") === True) {
    antwort = "Das ist schön"
  } else {
    antwort = "Das habe ich nicht verstanden."
  }
} while (1 === 1);

Thank you in Advance


Solution

  • You need to write boolean literals in all lowercase:

    (eingabe.includes("gut")===True) should be (eingabe.includes("gut")===true)

    EDIT

    I you prefer (I know I do), you can actually omit the === true part. .includes returns a boolean anyways:

    if (eingabe.includes("gut")) {
      //...
    }
    

    Does the same thing.