nuconuco
@nuconuco

Are you sure you want to delete the question?

If your question is resolved, you may close it.

Leaving a resolved question undeleted may help others!

We hope you find it useful!

jspでチェックボックスでチェックを付けた商品の合計金額を表示したいがjspの書き方がいまいちわからない

解決したいこと

jspでチェックボックスでチェックを付けた商品の合計金額を表示したい

発生している問題・エラー

出ているエラーメッセージを入力
タイプ 例外報告

メッセージ JSPのクラスをコンパイルできません:

説明 サーバーは予期しない条件に遭遇しました。それはリクエストの実行を妨げます。

例外

org.apache.jasper.JasperException: JSPのクラスをコンパイルできません: 

JSPファイル: [/goukei.jsp] の中の [20] 行目でエラーが発生しました
The operator += is undefined for the argument type(s) int, String[]
17: if (goukei!= null) {
18: 	while(total < goukei.length){
19: 		total++;
20: 		total += goukei;
21: 	}
22: }
23: 	out.println(goukei[total] + "円");

### 該当するソースコード
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
    <%
    	String[] goukei = request.getParameterValues("goukei");
    %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<div>
<p>
<%
	int total = 0;
if (goukei!= null) {
	while(total < goukei.length){
		total++;
		total += goukei;
	}
}
	out.println(goukei[total] + "円");
%>
</p>
		<p>購入する商品を選択くしてください。</p>
		<form action="whilePractice05.jsp" method="post">
			<input type="checkbox" name="goukei" value="120">鍋(3200円)<br>
			<input type="checkbox" name="goukei" value="198">フライパン(3300円)<br>
			<input type="checkbox" name="goukei" value="198">皿(110円)<br>
			<input type="checkbox" name="goukei" value="266">箸(211円)<br>
			<input type="checkbox" name="goukei" value="189">包丁(1200円)<br>
			<input type="checkbox" name="goukei" value="398">フォーク(120円)<br>
			<input type="checkbox" name="goukei" value="158">スプーン(130円)<br>
			<button type="submit">決定</button>
		</form>
</div>
</body>
</html>
### 自分で試したこと
↑
0

1Answer

total += goukei の部分でエラーが発生しています。これは、totalが整数型であるのに対し、goukeiは文字列の配列であるため、+= 演算子が使用できません。

out.println(goukei[total] + "円");の前のtotal++ で想定外に増えていませんか?
goukei[]のindex外の値になると思います。

<%
    int total = 0;
    if (goukei != null) {
        for (int i = 0; i < goukei.length; i++) {
            total += Integer.parseInt(goukei[i]);
        }
    }
    out.println(total + "円");
%>
1Like

Comments

  1. @nuconuco

    Questioner

    ありがとうございます!

Your answer might help someone💌