需要帮助制作循环工作

时间:2014-12-09 22:46:04

标签: java

我已经循环了我的代码,所以它一直重复,直到被问到“继续?”时给出“是”或“否”。但是我的代码在输入随机值后从循环中断开然后是。 例如:

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 个答案:

答案 0 :(得分: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;
    }
}