1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

JavaとJavaScriptの違い(平均の求め方)

Last updated at Posted at 2019-10-08

単純ではありますがこちらもアウトプット

#Java


import java.util.*;
public class Test12{
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
int sum = 0; //合計を保存するための変数
int a=0;
while (true) {
    System.out.println("数値を繰り返し入力して下さい(0で合計と平均をだして終了)"); //メッセージに終了条件を追加
    int num = scan.nextInt();
    if (num == 0) {
        break;
    } else {
        sum += num;
        a++;//おわるまで加算していく
        }
    }
//System.out.println("合計は"+sum);//
System.out.println("平均は"+sum/a);
 }
}

一例です。

#JavaScript

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8"/>
<title>jsave</title>
</head>
<body>
  <h1>平均の計算</h1>
  <input type="number" id="num" value="" placeholder="数値を入力"/>
  <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(){
//intに変換だがJavaと違いIntegerではない

  var num=parseInt(eleNum.value);
  nums.push(num);
  eleMsg.textContent=num+"を配列に追加";
}
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(",")}]の平均は${sum/nums.length}です。';
    eleMsg.textContent=msg;
}
</script>
</body>
</html>

とりあえずvarはブロックスコープ(let,const)に変えるべきなんでしょうな。

躓いた所で言えば


<script>
'use strict';
window.onload=function(){
  //dom取得
  let ele=document.getElementById("bt");
  let result=document.getElementById("result");
  //特定のイベントが対象に配信されるたびに呼び出される関数を設定します。 
  ele.addEventListener("click",function(){
    result.textContent="Clicked!";
  });
  ele.addEventListener("click",function(){
    window.alert("Clicked!!!");
  });
};
</script>

のようにHTMLを読み込んだ後にメソッドを実行?とか。。意味や意義を考えてたら理解が難しかったですね。。

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?