我无法使用此代码。我更熟悉python - javascript新手。这就是我的python等价物:
userinput = input("Enter the message you want to encryppt: ")
shift = int(input("How many letters do you want to shift by? "))
empty = ""
for char in userinput:
a = ord('a') if char.islower() else ord('A')
if char.isalpha():
firstord = ord(char) - a
realord = firstord + shift
realord = realord % 26
realord = realord + a
alpha = (chr(realord))
empty = empty + alpha
else:
notalpha = ("?")
empty = empty + notalpha
print(empty)
以下是javascript版本 - 我已经使用了评论。我的设置也有所不同。 (最后一个块是html)由于某种原因,它只显示按钮和输入框 - 但输出没有显示。
感谢您的帮助
<script>
function enterName(){
var userName = document.getElementById("word_in").value; //get the input string from the page
var shiftBy = Number(document.getElementById("shift").value); //get the amount of shift and convert it into a number. This Is IMPORTANT
var size= userName.length; //get the size of the input string
var encrypt="";
var temp = 0;
var i=0;
//step through the string 1 character at a time
for (i=0; i<size; i++){
//store the ASCII value of each character
temp=userName.charCodeAt(i){
// Uppercase
if ((temp >= 65) && (temp <= 90)){
temp = (((temp - 65 + shiftBy) % 26) + 65);
}
// Lowercase
else if ((temp >= 97) && (temp <= 122)){
temp = (((temp - 97 + shiftBy) % 26) + 97);
}
else {
temp = "?";
}
}
encrypt += String.fromCharCode(temp)
}
//output to the page
document.getElementById("word_out").innerHTML = encrypt;
}
</script>
&#13;
<body>
<p>Please enter your name:</p>
<input id="word_in">
<p>Please enter the shift:</p>
<input id = "shift">
<button type = "button" onclick="enterName()"></button>
<p id = "word_out"></p>
</body>
&#13;
答案 0 :(得分:1)
你有一个开放的花括号和一个结束花括号太多。见评论。
function enterName() {
var userName = document.getElementById("word_in").value; //get the input string from the page
var shiftBy = Number(document.getElementById("shift").value); //get the amount of shift and convert it into a number. This Is IMPORTANT
var size = userName.length; //get the size of the input string
var encrypt = "";
var temp = 0;
var i = 0;
//step through the string 1 character at a time
for (i = 0; i < size; i++) {
//store the ASCII value of each character
temp = userName.charCodeAt(i); //{ <------------------------------------ too much
// Uppercase
if ((temp >= 65) && (temp <= 90)) {
temp = (((temp - 65 + shiftBy) % 26) + 65);
}
// Lowercase
else if ((temp >= 97) && (temp <= 122)) {
temp = (((temp - 97 + shiftBy) % 26) + 97);
}
else {
temp = "?";
}
//} <------------------------------------------------------------------- too much
encrypt += String.fromCharCode(temp);
}
//output to the page
document.getElementById("word_out").innerHTML = encrypt;
}
<p>Please enter your name:</p>
<input id="word_in">
<p>Please enter the shift:</p>
<input id="shift">
<button type="button" onclick="enterName()"></button>
<p id="word_out"></p>
答案 1 :(得分:0)
我在这里创建了一个工作示例: https://jsfiddle.net/w4rafn1j/2/
以下行后面需要一个分号而不是一个块,因为它是一个函数调用:
temp=userName.charCodeAt(i);