我循环提示,要求用户输入一个整数并使用冒泡排序方法对其进行排序并将其打印在输出中。点击时我需要一个按钮,要求用户输入4个数字并将它们作为整数输出,然后在我提供的空数组的HTML页面中进行排序和打印。我只是需要帮助了解如何设置它,因为我一直在努力,而不是正确的。不是狂热的编码员。
<!DOCTYPE html>
<html>
<head>
<title>User Input, Sort and Find!</title>
<style>
</style>
</head>
<body>
<h2>Enter 4 numbers user!</h2>
<p id="myprint"></p>
<button onclick="userInput()">Input your Numbers!</button>
<button onclick="searchInput()">Find an inputed number in your array </button>
<script>
var numbers = [];
function userInput() {
for(var i = 0; i < 4; i++){
numbers.push(prompt("Enter a number 1 at a time, from 1-9 until prompts ask you 4 times:"));
if (numbers[i] = NaN) {
alert("Enter a number!");
} else if( numbers[i] % 1 == 0) {
alert("Enter a whole number!")
}
}
}
//Sort the array and print numbers in inner html
function bubbleSort(numbers) {
var length = numbers.length;
for (var i = (length - 1); i >= 0; i--) {
for (var j = (length - i); j > 0; j--) {
if (numbers[j] < numbers[j - 1]) {
var nmbr = numbers[j];
numbers[j] = numbers[j - 1];
numbers[j - 1] = nmbr;
}
}
}
}
function searchInput() {
}
document.getElementById("myprint").innerHTML = "Your numbers are" + numbers;
</script>
</body>
</html>
答案 0 :(得分:0)
我查看了你的代码,似乎有一些我能发现的错误。
for(var i = 0; i < 4; i++){
numbers.push(prompt("Enter a number 1 at a time, from 1-9 until prompts ask you 4 times:"));
if (numbers[i] = NaN) { // this is the wrong logic ...
alert("Enter a number!");
} else if( numbers[i] % 1 == 0) { **// this is not correct because your basically saying every integer number is not a whole number.**
alert("Enter a whole number!")
}
}
}
我在下面为你的循环提供的算法提示用户考虑所有可能出错的场景并处理它们,至少这应该为你提供一个很好的基础,可以随时移动到你想做的事情上。
for(var i = 0; i < 4; i++){
var num = prompt("Enter a number 1 at a time, from 1-9 until prompts ask you 4 times:");
if (isNaN(num)) {
alert("Enter a number!");
--i; // reset the counter for amount of numbers entered
}
if( !isNaN(num)) {
if( num % 1 != 0){
alert("Enter a whole number!")
--i; // reset the counter for amount of numbers entered
}else{
numbers.push(num);
}
}
}