java
java

Reputation: 17

I cannot figure out how I can fix this if statement

var count=1;
var temp="";
var end= window.prompt('enter the length');
var b = parseInt(end);

while(true){
  temp+="-";
  count++;
  if(count>b&&end!=null){
console.log("enter:" +end+ "= " + temp );
break;
 }
}

I have this code which is suppose to give me the output of "-" for each number the user enters so if i the user enters 2 the output should be "--". But when the user enters a string or number zero the output should be just "-".

Upvotes: 0

Views: 80

Answers (2)

Sean Kinsey
Sean Kinsey

Reputation: 38046

This is really just a simpler way of doing what you want, as comments say, isNaN is what you need to verify you actually get a number.

var length = parseInt(window.prompt('enter the length'), 10);
alert(new Array(isNaN(length) ? 2 : length  + 1).join('-'));

Upvotes: 1

Zeb Rawnsley
Zeb Rawnsley

Reputation: 2220

var count = 1;
var temp = "";
var end = window.prompt('enter the length');
var b = parseInt(end);

while (true) {
    temp += "-";
    count++;

    // if the user entered a valid integer that is not 0
    if (!isNaN(b) && b !== 0) {
        if (count > b && end != null) {
            console.log("enter:" + end + "= " + temp);
            break;
        }

    // else the user entered 0 or some other input that isn't an integer
    } else {
        console.log("enter:" + end + "= -");
        break;
    }
}​

FIDDLE

FIDDLE WITH ALERTS

Upvotes: 0

Related Questions