2017-12-02 3 views
1

달러 금액을 읽고 그 값을 다시 인쇄하는 장바구니를 디자인하려고합니다. 그러나 My while 루프는 종료되지 않고 arraylist는 잘못된 값을 저장합니다.ArrayList 용 Java While 루프가 종료되지 않습니다.

Correct output

을하지만 내 출력 :

/** 
* This method is the shopping cart 
*/ 
public static void shoppingCart() 
{ 
    // create scanner objects 
    Scanner textReader = new Scanner(System.in); 
    Scanner numberReader = new Scanner(System.in); 
    // declare variables 
    int counter = 0; 
    // create arraylist object 
    ArrayList<Double> cartItems = new ArrayList<Double>(); 
    // create decimal format object 
    DecimalFormat dollarformatter = new DecimalFormat("$#0.00"); 
    // print out the first prompt 
    System.out.print("Would you like to input item/s - y/n: "); 
    String response = textReader.nextLine(); 
    System.out.println(); 
    // create while loop to restrict responses to single characters 
    while ((!response.equalsIgnoreCase("y")) && (!response.equalsIgnoreCase("n"))) 
    { 
     System.out.print("Sorry - we need a y/n: "); 
     response = textReader.nextLine(); 
     System.out.println(); 
    } 
    // create while loop for positive response 
    while ((response.equalsIgnoreCase("y"))) 
    { 
     System.out.print("Please enter an item price, or -1 to exit: $"); 
     double values = numberReader.nextDouble(); 
     cartItems.add(values); 
     if ((values > (-1))) 
     { 
      System.out.print("Please enter another item price, or -1 to exit: $"); 
      values = numberReader.nextDouble(); 
      cartItems.add(values); 
     } 
     else if ((values <= (-1))) 
     { 
      System.out.println(); 
      System.out.println("********** Here are your items **********"); 
      System.out.println(); 
      for (counter = 0; counter < cartItems.size(); counter++) 
      { 
       System.out.println("Item #" + (counter + 1) + ": " + cartItems.get(counter)); 
      } 
     } 
    } 
    System.out.println(); 
    System.out.println("********** Thank you for using the shopping cart **********"); 
} 

결과는 다음과 같아야합니다

my output

  • 루프가 종료하고 다시 이동하지 않지만 첫 번째 프롬프트에 "상품 가격을 입력하십시오. 종료하려면 -1을 입력하십시오 :"
  • 프로그램은 arraylist의 일부로 "-1"을 계속 계산합니다. "-1"값은 "no"로 작동하고 arrayList에 더 많은 요소를 추가하는 것을 끝내지 만 내 코드에서는 arrayList에 흡수됩니다. 나는 "-1"을 문자열로 바꾸어 "무시"하도록 프로그램을 시도했지만 작동하지 않습니다.
  • 프로그램이 최종 항목을 나열한 후 (사용자 출력에서 ​​# 3) 사용자가 항목을 삭제할지 묻는 메시지가 표시됩니다. 나는 while 회 돌이가 종료를 거부하는 이유와 "-1"이 내 arraylist에 계속 포함되는 이유에 관해서는 꽤 난처한 것으로서 나는 여기까지 오지 않았다. 내가 운이없는 지금 하루 동안 이것에 대해 궁리 해 왔기 때문에 이것에 대한 어떤 도움도 크게 감사합니다.

업데이트 된 코드; 루프 종료 문제가 해결 된 것처럼 보이지만 "-1"이 종료를 트리거하지 않고 여전히 arrayList에 추가되고 있습니다.

while ((response.equalsIgnoreCase("y"))) { 
    System.out.print("Please enter an item price, or -1 to exit: $"); 
    double values = numberReader.nextDouble(); 
    cartItems.add(values); 
    while ((values != (-1))) { 
    System.out.print("Please enter another item price, or -1 to exit: $"); 
    values = numberReader.nextDouble(); 
    cartItems.add(values); 
    } 
    System.out.println(); 
    System.out.println("********** Here are your items **********"); 
    System.out.println(); 
    for (counter = 0; counter < cartItems.size(); counter++) { 
    System.out.println("Item #" + (counter + 1) + ": " + cartItems.get(counter)); 
    } 
    break; 
} 
+1

else if 문은 여전히 ​​while 루프 안에 있으므로 프롬프트가 다시 인쇄됩니다. 어쩌면 휴식 진술서를 넣는 것을 고려해야합니까? 또한 if 및 else 문 앞에 값을 장바구니에 추가하므로 여전히 -1이 추가됩니다. – Meepo

+0

"-1"을 "종료"로 읽지 않는 이유를 설명 할 수 있습니까? "-1"을 입력해도 코드는 계속 실행됩니다. – iMagicMango

+0

while 루프는 조건이 true 일 때 반복을 계속합니다.if else 문은 입력되지만 while 루프의 맨 위로 돌아갑니다. – Meepo

답변

1

문제 1 : cartItems.add (값)은 if 문보다 먼저 발생합니다. 즉 -1이 계속해서 장바구니에 추가됩니다. 즉, 0보다 아래에 있는지 테스트하기 전에 카트에 값을 추가하는 것입니다.

문제 2 : else가 실행되면 while 루프에 있고 응답이 변경되지 않았으므로 while 루프 조건이 여전히 true이므로 사용자에게 다시 묻습니다. else if 문 끝 부분에 break 문을 넣는 것이 좋습니다. 하지만 제 코드는 그 필요성을 제거합니다.

if((response.equalsIgnoreCase("y"))) 
{ 
    System.out.print("Please enter an item price, or -1 to exit: $"); 
    double values = numberReader.nextDouble(); 
    while ((values > (-1))) 
    { 
     cartItems.add(values); 
     System.out.print("Please enter another item price, or -1 to exit: $"); 
     values = numberReader.nextDouble(); 
    } 
} 
System.out.println(); 
System.out.println("********** Here are your items **********"); 
System.out.println(); 
for (counter = 0; counter < cartItems.size(); counter++){ 
     System.out.println("Item #" + (counter + 1) + ": " + cartItems.get(counter)); 
} 
System.out.println(); 
System.out.println("********** Thank you for using the shopping cart **********"); 

을 당신이 필요로하는 모든 당신이 조기 전에 장바구니에 추가 할 필요가 없습니다 것 같은 것을 while 루프를 할 수있는 방법임을 깨닫게되었다 내가 한 기본적으로 무엇을 : 여기

내가 어떻게 할 것인지의 이전 코드에서했던 것처럼 0 이하임을 알았습니다. 울타리 게시 문제를 조사하는 것이 좋습니다. 담장 게시는 | - | - | 그래서 펜스 포스트는 당신의 프롬프트 였고 전선은 값을 더하고있었습니다. 따라서 주문을 전환했기 때문에 제 방식이 더 좋습니다. 그것만큼이나 간단합니다.

+0

루프 종료 문제를 해결했지만 -1이 여전히 추가되고 있다고 생각합니다. – iMagicMango

+0

if 문 안에 cartItems.add (values)를 넣고 if 문 전에 제거 했습니까? – Meepo

+0

실제로 if/else 문을 완전히 삭제했습니다. 대신, 나는 while 문을 사용했다. 위의 원래 게시물 코드를 업데이트했습니다. if/else 문을 사용하는 것이 좋습니다. 나는 언젠가 성명서로 사물을 분명히 할 수 있다고 생각했습니다. – iMagicMango

0

당신이이 점을 명심하여 여러 다른 조건 내부 루프. 루프가 완료 될 때까지 계속 실행됩니다.

관련 문제