+ 연산자를 java.lang.String과 void 유형에 대해 적용할 수 없다. 라는 뜻이다.
메소드를 void로 리턴 값 없이 만들고 그 메소드를 불러오는 곳을 System.out.println 안에서 불러왔더니 난 오류이다.
즉 String과 값을 반환하지 않는 void 메서드를 연결하려고 하면 발생한다.
package static2.ex;
public class MathArrayUtils {
private static int sum;
double avg;
int min;
int max;
private MathArrayUtils(){
}
public static void sum(int[] values){ // 이 메소드
for (int value : values) {
sum += value;
}
System.out.println("sum = " + sum);
}
}

해결방안
1. 메소드에 반환 값을 추가하기
2. 메서드 호출 결과를 문자열 다음에 불러오기.
1번 해결방안
package static2.ex;
public class MathArrayUtils {
private static int sum;
double avg;
int min;
int max;
private MathArrayUtils(){
}
public static int sum(int[] values){ // return 값 추가
for (int value : values) {
sum += value;
}
return sum;
}
}
package static2.ex;
public class MathArrayUtilsMain {
public static void main(String[] args) {
int[] values = {1, 2, 3, 4, 5};
System.out.println("sum = " + MathArrayUtils.sum(values));
}
}

2번 해결 방안
package static2.ex;
public class MathArrayUtils {
private static int sum;
double avg;
int min;
int max;
private MathArrayUtils(){
}
// public static int sum(int[] values){
// for (int value : values) {
// sum += value;
// }
// return sum;
// }
public static void sum(int[] values){
for (int value : values) {
sum += value;
}
System.out.println(sum);
}
}
package static2.ex;
public class MathArrayUtilsMain {
public static void main(String[] args) {
int[] values = {1, 2, 3, 4, 5};
System.out.print("sum = "); // println을 print로 바꾸고
MathArrayUtils.sum(values); // 밑에서 함수호출
}
}

'오류, 기능, 문제해결(JAVA)' 카테고리의 다른 글
| System.out.println() 에 기본형 변수 넣을때 동작 원리? (0) | 2025.01.09 |
|---|---|
| 계산기과제 레벨2 (0) | 2025.01.09 |
| Recursive constructor call (0) | 2025.01.03 |
| 자연수 n을 뒤집어 각 자리 숫자를 원소로 가지는 배열 형태로 리턴 (0) | 2025.01.01 |
| 자연수 각 자릿수의 합을 구하기 (1) | 2024.12.31 |