2017-12-17 18 views
1

if 문이 너무 많아서 더 단순화 할 수있는 방법이 있습니까? 나는 그것을 다소 줄 였지만 아마도 더 효율적인 해결책이있을 것입니까? 미리 감사드립니다!이 코드를 단순화하기위한 추가 방법이 있습니까?

Scanner enterPrice = new Scanner(System.in); 
double budgetRemaining = 100, itemPrice; 

while (budgetRemaining > 0) { 
    System.out.println("You have a remaining budget of $" + budgetRemaining + ". Please enter price of item:"); 
    System.out.println(itemPrice = enterPrice.nextDouble()); 

    if (itemPrice < budgetRemaining) { 
     budgetRemaining -= itemPrice; 

     if (itemPrice < 0) { 
      budgetRemaining += itemPrice; 
      System.out.println("Sorry, you have entered an invalid amount. "); 
     } 
    } 
    else if (itemPrice > budgetRemaining) { 
     System.out.println("Sorry, your item exceeds your budget."); 
    } 

    if (itemPrice == budgetRemaining) { 
     budgetRemaining = 0; 
     System.out.println("You have reached your maximum budget. Thank you for shopping with us!"); 
    } 
}  
+5

코드가 이미 작동 중이며 작업 코드를 검토하는 몇 쌍의 눈을 갖고 자한다면 자매 사이트 [Code Review] (https://codereview.stackexchange.com)가 이 질문. –

+0

아이템 가격이 남은 예산보다 적거나 크지 않다고 이미 주장했기 때문에 'if (itemPrice == budgetRemaining)'를 완전히 다른 것으로 대체 할 수 있습니다. 같은. –

+0

지금 교체되었습니다. 그리고 나중에 사용할 코드 검토를 제안 할 것이고 제안에 감사 할 것입니다. –

답변

1

모든 부정적인 조건을 먼저 검사하여 조금 더 단순화 할 수 있습니다.

Scanner enterPrice = new Scanner(System.in); 
    double budgetRemaining = 100, itemPrice; 
    while (budgetRemaining > 0) { 
     System.out.println("You have a remaining budget of $" + budgetRemaining + ". Please enter price of item:"); 
     System.out.println(itemPrice = enterPrice.nextDouble()); 
     if (itemPrice < 0) { 
      System.out.println("Sorry, you have entered an invalid amount. "); 
     } else if (itemPrice > budgetRemaining) { 
      System.out.println("Sorry, your item exceeds your budget."); 
     } else if (itemPrice == budgetRemaining) { 
      budgetRemaining = 0; 
      System.out.println("You have reached your maximum budget. Thank you for shopping with us!"); 
     } else { 
      budgetRemaining -= itemPrice; 
     } 
    }  
} 
2

이동 네거티브 가격 체크

감아 제 if 블록의 체크 아웃 itemPrice < 0. 이 오류 검사는 첫 번째 코드 경로뿐만 아니라 모든 코드 경로에 있어야합니다. 예산에서 공제하기 전에 부정적인 가격에 대한 점검에 다시 추가 할 필요에서 당신을 유지합니다.

while (budgetRemaining > 0) { 
    System.out.println("You have a remaining budget of $" + budgetRemaining + ". Please enter price of item:"); 
    itemPrice = enterPrice.nextDouble(); 

    if (itemPrice < 0) { 
     System.out.println("Sorry, you have entered an invalid amount. "); 
     continue; 
    } 

    ... 
} 

내가 다음 <==가지 경우를 결합 할 경우

을 결합합니다. 로직을 가능한 한 비슷하게 유지하십시오. 항상 itemPrice을 빼십시오. 유일한 차이점은 완료되면 메시지를 인쇄한다는 것입니다. 루프 상태를 확인했기 때문에 최종 인쇄물을 루프 바깥으로 옮기고 if (itemPrice == budgetRemaining) 검사를 완전히 제거 할 수 있습니다.

while (budgetRemaining > 0) { 
    System.out.println("You have a remaining budget of $" + budgetRemaining + ". Please enter price of item:"); 
    itemPrice = enterPrice.nextDouble(); 

    if (itemPrice < 0) { 
     System.out.println("Sorry, you have entered an invalid amount. "); 
     continue; 
    } 

    if (itemPrice <= budgetRemaining) { 
     budgetRemaining -= itemPrice; 
    } 
    else if (itemPrice > budgetRemaining) { 
     System.out.println("Sorry, your item exceeds your budget."); 
    } 
} 

System.out.println("You have reached your maximum budget. Thank you for shopping with us!"); 

ifelse if 확인 지금 바로 어느 쪽 else if

때문에 중복이, 두 번째는 간단한 else 될 수 있습니다 제거합니다.

if (itemPrice <= budgetRemaining) { 
    budgetRemaining -= itemPrice; 
} 
else { 
    System.out.println("Sorry, your item exceeds your budget."); 
} 

조기 종료, 내가 먼저 예산을 초과 확인하도록하기 위해 전환 할 것 제외

. 우리는 itemPrice < 0 점검을하고 있기 때문에, 앞의 다른 오류 조건도 점검하는 것이 좋습니다. budgetRemaining -= itemPrice 문은 지금 어떤 상태의 밖에 :

while (budgetRemaining > 0) { 
    System.out.println("You have a remaining budget of $" + budgetRemaining + ". Please enter price of item:"); 
    itemPrice = enterPrice.nextDouble(); 

    if (itemPrice < 0) { 
     System.out.println("Sorry, you have entered an invalid amount. "); 
     continue; 
    } 

    if (itemPrice > budgetRemaining) { 
     System.out.println("Sorry, your item exceeds your budget."); 
     continue; 
    } 

    budgetRemaining -= itemPrice; 
} 

System.out.println("You have reached your maximum budget. Thank you for shopping with us!"); 

continue으로 종료 초기 오류 검사 +의이 스타일

쉽게 정규 경우이 무엇인지 볼 수 있습니다. 주요 코드 경로로 승격되었습니다. 다른 수표와 출력물은 전제 조건입니다.

또는 if/else 체인으로 작성할 수 있습니다. 둘 중 하나가 작동합니다. 이제는 문학적 취향에 관한 것입니다.

if (itemPrice < 0) { 
    System.out.println("Sorry, you have entered an invalid amount. "); 
} 
else if (itemPrice > budgetRemaining) { 
    System.out.println("Sorry, your item exceeds your budget."); 
} 
else { 
    budgetRemaining -= itemPrice; 
} 
+0

코드 전반에 걸쳐 다른 오류 검사를 추가하여 복잡하다고 생각합니다. 'continue' 문으로 시작 부분에 조건을 추가하는 것이 훨씬 간단합니다. 이것은 내가 배우기를 바라고 있었던 것입니다. 정말로 시간을내어 주셔서 감사합니다! 고마워요! –

0

는 여기가 예산 항목의 값을 제거하기 전에 조건에 해당하는 경우 내가 확인하고있어 내 코드

while (budgetRemaining > 0) { 
     System.out.println("You have a remaining budget of $" + budgetRemaining + ". Please enter price of item:"); 
     itemPrice = enterPrice.nextDouble(); 

     if (itemPrice < 1){ 
      System.out.println("Sorry, you have entered an invalid amount. "); 
     } 
     else if (itemPrice > budgetRemaining) { 
      System.out.println("Sorry, your item exceeds your budget."); 
     } 
     else{ 
      budgetRemaining -= itemPrice; 
     } 
    }  
System.out.println("You have reached your maximum budget. Thank you for shopping with us!"); 

입니다. itemPrice가 유효하다는 것을 안다면 그냥 뺄셈을 계속합니다.

또한 돈이 없어지면 while 루프가 자동으로 종료되므로 실제 종료 전에 잔액을 확인할 필요가 없습니다. 나중에 성명을 인쇄 할 수도 있습니다.

내가 한 또 다른 사소한 일은 항목이 완전히 무료가 될 수 없다고 가정하기 때문에1을 설정하는 것이 었습니다.