2014-12-09 6 views
-3

"계속 하시겠습니까?"라는 질문에 "예"또는 "아니오"가 나타날 때까지 반복되도록 내 코드를 반복했습니다. 하지만 무작위 값을 입력 한 후 루프에서 코드가 나옵니다. 예를 들면 :루프 작업을 수행하는 데 도움이 필요합니다.

Add or delete another name? Add 
Please enter a name you want to add: Matt 
Continue? f 
Continue? yes 

그것은 말해야한다 :

Add or delete another name? Add 
Please enter a name you want to add: Matt 
Continue? f 
Continue? yes 
Add or delete another name? 

실제 코드

import java.io.File; 
import java.io.PrintWriter; 
import java.util.ArrayList; 
import java.util.Scanner; 


public class AddOrDeleteNames { 
public static void main(String[] args) throws Exception { 

    ArrayList<String> names = new ArrayList<String>(); 
    Scanner scan = new Scanner(new File("names.txt")); 
    Scanner myScan = new Scanner(System.in); 
    Scanner scanRedo = new Scanner(System.in); 
    String userRedo; 
    String userResponse; 

    while (scan.hasNext()) 
     names.add(scan.next()); 

    do {  
     System.out.print("Add or delete another name? "); 
     userResponse = myScan.next(); 

     if (userResponse.equalsIgnoreCase("add")) { 
     System.out.print("Please enter a name you want to add: "); 
     names.add(myScan.next()); 
     } else if (userResponse.equalsIgnoreCase("delete")) { 
     System.out.print("Please enter a name you want to delete: "); 
     names.remove(myScan.next()); 
     } else { 
     System.out.print("Invalid Choice"); 
     } 

     PrintWriter writer = new PrintWriter("namesupdated.txt"); 
     for (int i = 0; i < names.size(); i++) 
     writer.println(names.get(i)); 

     writer.close(); 

     System.out.print("Continue? "); 
     userRedo = scanRedo.next(); 
    } while (userRedo.equalsIgnoreCase("yes")); 

    do { // THIS LOOP IS HERE BECAUSE IF THE USER ENTERS A VALUE OTHER THAN CONTINUE, YES OR NO, THE QUESTION REPEATS 
     if(userRedo.equalsIgnoreCase("no")) { 
      System.out.print("Thank You."); 
      userRedo = scanRedo.next(); 
     } else if (!userRedo.equalsIgnoreCase("yes")) { 
      System.out.print("Continue? "); // LOOP ENDS EARLY HERE 
      userRedo = scanRedo.next(); 
     } 
    } while (!userRedo.equalsIgnoreCase("yes")); // NOT SURE HOW TO RESTART PREVIOUS LOOP 

    scan.close(); 
    myScan.close(); 
    scanRedo.close(); 
} 
} 
+1

매우 영리합니다. .. 이전의 [question] (답을 가지고) (http://stackoverflow.com/questions/27384270/breaks-from-loop)을 "파괴"하고 똑같은 코드로 새로운 것을 만듭니다. – Tom

+0

이전 코드가 잘못되었으므로 코드를 수정했습니다. –

+2

마지막 부분의 주석을 제외하고는 차이점을 볼 수 없습니다. 게다가 새로운 질문을 만드는 대신 이전 질문을 업데이트 ("파기"하지 말아야 함)해야합니다. – Tom

답변

0

이 작업을 수행하는 방법은 변하기 쉬워 조건의 일종으로 while 루프로 항상 :

Scanner scan = new Scanner(System.in); 

boolean stop = false; 
while(!stop) { 
    //do whatever 

    ... 

    System.out.println("Continue? Yes or No"); 
    String s = Scan.nextLine(); 
    if(s.equals("No")) { 
     stop = true; 
    } 
} 
+0

죄송합니다. 작동하지 않습니다. –

관련 문제