Simple but also output
Java
import java.util.*;
public class Test12{
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
int sum = 0; //Variables for storing totals
int a=0;
while (true) {
System.out.println("Please enter the number repeatedly(End with 0 for total and average)"); //Add termination condition to message
int num = scan.nextInt();
if (num == 0) {
break;
} else {
sum += num;
a++;//Add until the end
}
}
//System.out.println("The total is"+sum);//
System.out.println("The average is"+sum/a);
}
}
This is an example.
JavaScript
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8"/>
<title>jsave</title>
</head>
<body>
<h1>Average calculation</h1>
<input type="number" id="num" value="" placeholder="Enter a number"/>
<button onclick="add()">Add</button>
<button onclick="btCalc()">Calc!</button>
<div id="msg"></div>
<script>
var nums=[];
var str="";
var eleNum=document.getElementById("num");
var eleMsg=document.getElementById("msg");
function add(){
//Converted to int but not Integer unlike Java
var num=parseInt(eleNum.value);
nums.push(num);
eleMsg.textContent=num+"To the array";
}
function btCalc(){
var sum=0;
for(var i=0;i<nums.length;i++){
str +=nums[i]+(i==nums.length-1?"":",");
sum +=nums[i];
}
document.getElementById("data").textContent=str;
var msg='[{${nums.join(",")}]The average of${sum/nums.length}is.';
eleMsg.textContent=msg;
}
</script>
</body>
</html>
For the time being, var should be changed to block scope (let, const).
Speaking where I stumbled
<script>
'use strict';
window.onload=function(){
//dom get
let ele=document.getElementById("bt");
let result=document.getElementById("result");
//Sets a function that is called each time a particular event is delivered to the target.
ele.addEventListener("click",function(){
result.textContent="Clicked!";
});
ele.addEventListener("click",function(){
window.alert("Clicked!!!");
});
};
</script>
Execute the method after loading the HTML like? And. .. It was difficult to understand when considering the meaning and significance. ..
Recommended Posts