我有这个功能
public static void main(String args[]){
String first="", second="";
String x="animal",vegetable,mineral;
Scanner s=new Scanner(System.in);
System.out.println("TWO QUESTION!");
System.out.println("Think of an object, and I'll try to guess it.");
System.out.println("Is it animal, vegetable, or minaral?");
first=s.next();
if (first==x){
System.out.println("Is it bigger than a breadbox");
second=s.next();
if(second=="yes"){
System.out.println("My guess id that you are thinking of a mouse");
System.out.println("I would ask you but i really dont care.");
}else{
System.out.println("My guess id that you are thinking of a squirrel");
System.out.println("I would ask you but i really dont care.");
}
}else if (first=="vegetable"){
if(second=="yes"){
System.out.println("My guess id that you are thinking of a watermelon");
System.out.println("I would ask you but i really dont care.");
}else{
System.out.println("My guess id that you are thinking of a carrot");
System.out.println("I would ask you but i really dont care.");
}}else if (first=="mineral"){
if(second=="yes"){
System.out.println("My guess id that you are thinking of a Camero");
System.out.println("I would ask you but i really dont care.");
}else{
System.out.println("My guess id that you are thinking of a paper clip");
System.out.println("I would ask you but i really dont care.");
}
}
}
上面的代码给出了错误
未捕获RangeError:超出最大调用堆栈大小
我还想知道在使用
时是否有任何方法可以使用JavaScript切换类function flicker(length) {
$("p:nth-child(" + (Math.random() * length) + ")").toggleClass('off');
setTimeout(flicker(length), Math.random()*1000);
}
我收到错误
未捕获的TypeError:无法读取属性'切换'未定义的
如何解决这些问题?
感谢。
答案 0 :(得分:2)
调试后我发现了2个问题。
Math.random() * length
返回一个浮点数,因此您需要进行舍入。setTimeout
可以通过在延迟length
参数来接受函数
醇>
window.setTimeout(func,[delay,param1,param2,...]);
function flicker(length) {
$("p:nth-child(" + Math.round(Math.random() * length) + ")").toggleClass('off');
setTimeout(flicker, Math.random() * 1000, length);
}
flicker(5)
.off {
color: white;
font-weight: bold;
background-color: black
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>1</p>
<p>2</p>
<p>3</p>
<p>4</p>
答案 1 :(得分:0)
使用setTimout时,必须将flicker(length)
包装在函数中:
function flicker(length) {
$("p:nth-child(" + (Math.random() * length) + ")").toggleClass('off');
setTimeout(function(){flicker(length);}, Math.random()*1000);
}
否则它总是被调用,导致类似这样的事情:
function foo(){
foo();
}
foo();
只会创建一个无限循环,并会导致与您描述的相同的堆栈错误。
答案 2 :(得分:0)
问题是因为您通过将结果设置为flicker()
而无法传递其引用,从而在无限循环中调用setTimeout
。您需要为setTimeout()
调用匿名函数。试试这个:
function flicker(length) {
$("p:nth-child(" + (Math.random() * length) + ")").toggleClass('off');
setTimeout(function() {
flicker(length)
}, Math.random()*1000);
}