TIL

(2024-04-25) 자바 개인과제 level 1

o_coding 2024. 4. 25. 20:35

계산기 만들기 level 1 

 

배열로 조회 구현

package level1;

import java.util.Scanner;

public class Main {
public static void main(String[] args) {
Calculate[] calList = new Calculate[10]; //계산 조회 리스트
Scanner sc = new Scanner(System.in);
int count = 0;
String stop;
while (true){

System.out.println("첫번째 숫자를 입력하세요 : ");
double firstNum = sc.nextDouble();
sc.nextLine();
System.out.println("두번째 숫자를 입력하세요 : ");
double secondNum = sc.nextDouble();
sc.nextLine();
System.out.println("연산자를 입력하세요 : ");
String operator = sc.nextLine();
Calculate calculate = new Calculate(firstNum,secondNum,operator.charAt(0));

if(operator.equals('/') || secondNum==0){
System.out.println("나눗셈 연산중 분모를 0으로 할 수 없습니다.");
continue;
}

System.out.println("계산 결과입니다 : " + calculate.operate());
if(count==10){
for (int i = 0; i < calList.length-1 ; i++) {
calList[i] = calList[i+1];
}
calList[calList.length-1] = calculate;
}else{
calList[count] = calculate;
count++;
}
System.out.println("더 계산하시겠습니까? (exit 입력 시 종료)");
stop = sc.nextLine();
if (stop.equals("exit")){
break;
} else if (stop.equals("inquiry")) { //계산 조회 로직
for (int i = 0;i < count; i++) {
System.out.println(calList[i].toString());

}

}
}

}
}

exit를 입력하면 종료하고 inquiry를 입력하면 조회하도록 구현

한참 해맸던 부분이 리스트에 결과를 추가할 때 배열이 꽉찬 경우 첫번째 인덱스를 삭제하고 마지막 인덱스에 추가하는 방식인대 count설정을 잘못해서 결과가 다르게 나왔다.

if(count==9){ //잘못된 경우
for (int i = 0; i < calList.length-1 ; i++) {
calList[i] = calList[i+1];
}
calList[calList.length-1] = calculate;
}else{
calList[count] = calculate;
count++;
}

처음에 실수로 count==9로 if문을 걸었는대 그렇게 되면 마지막 인덱스 calList[9] 에 값이 들어가기전에 if문에 진입하게된다.

if(count==10){

10으로 변경하니 잘 작동했다.

 

ArrayList로 저장공간 변경

List<Calculate> calList = new ArrayList<>();

 

사이즈 제한도 없어지고 추가도 편해져서 코드가 간단해졌다.

calList.add(calculate);