-1

So essentially what I'm trying to do is to figure out how to repeat a line x number of times based on a prompt's output.

i.e

<script>
var favnumber = Number(prompt("What is your favorite number?"))
for(var i=0;i<favnumber;i++){
    System.out.println(name + "is bad at javascript");
}
</script>

any idea whats wrong?

j08691
  • 190,436
  • 28
  • 232
  • 252
  • 2
    Did you define a function `System.out.println()` somewhere? This is no native JavaScript function! – Sirko Oct 20 '12 at 19:55

2 Answers2

0

JavaScript is not Java. So there is no function System.out.println() unless you define it.

To output you hav either to user the DOM, console or alert. The later might look like this:

<script>
var favnumber = Number(prompt("What is your favorite number?"));
var name = 'Bob';
for(var i=0;i<favnumber;i++){
   alert(name + " is bad at javascript");
}
</script>

Besides, try to get used to end every command with ;. Otherwise you run into many weird problems as a JavaScript beginner - and later as well.

Sirko
  • 65,767
  • 19
  • 135
  • 167
0

JavaScript is not Java, so System.out.println doesn't have any special meaning. You have two options here: to use console.log(), or to use document.write().

I recommend you use console.log(), as it doesn't mess with the current page's HTML structure:

var favnumber = parseInt(prompt("What is your favorite number?"), 10);
var name = 'JavaScript';

for (var i = 0; i < favnumber; i++) {
    console.log(name + ' is not Java');
}​

You'll need to open up your browser's JavaScript console to see those messages.

Using document.write() is a bit more cumbersome:

var favnumber = parseInt(prompt("What is your favorite number?"), 10);
var name = 'JavaScript';

for (var i = 0; i < favnumber; i++) {
    document.write(name + ' is not Java');
    document.write('<br />');
}​

Demo: http://jsfiddle.net/HC3Y2/

Blender
  • 257,973
  • 46
  • 399
  • 459
  • I'd rather not recommend starters to use `document.write`. You know the [reasons](http://stackoverflow.com/q/802854/1331430) for this very well but starters most likely don't. – Fabrício Matté Oct 20 '12 at 20:09