java 无法退出循环[已关闭]

ivqmmu1c  于 2023-02-07  发布在  Java
关注(0)|答案(2)|浏览(118)

19小时前关门了。
Improve this question
我 * 是 * 试图使一个小程序,将采取用户的数据,当用户将打印"列表",它会显示所有的数据,并结束程序,但它不会结束。

import java.util.Scanner;
import java.util.TreeSet;

public class test {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        String email = scanner.nextLine();
        TreeSet<String> address = new TreeSet<>();
        while (true) {

            address.add(email);

            if (email.equals("LIST")) {
                for (String i : address) {
                    System.out.println(i);
                }
            }
        }
    }
}
hts6caw3

hts6caw31#

您的代码不会停止程序。
一种实现方法是在while循环中测试布尔值而不是true,当用户输入LIST时,可以将布尔值设置为false,这里我添加了这样一个变量,并将其命名为shouldEnd

import java.util.Scanner;
import java.util.TreeSet;

public class test {
   public static void main(String[] args) {
      Scanner scanner = new Scanner(System.in);
      String email = scanner.nextLine();
      TreeSet<String> addres = new TreeSet<>();
      boolean shouldEnd = false;
      while (!shouldEnd) {
         addres.add(email);
            
         if (email.equals("LIST")) {
            for (String i : addres) {
               System.out.println(i);
            }
            shouldEnd = true;
         }
      }
   }
}
8nuwlpux

8nuwlpux2#

use:

import java.util.Scanner;
import java.util.TreeSet;

public class test {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        String email = scanner.nextLine();
        TreeSet<String> address = new TreeSet<>();
        while (true) {

            address.add(email);

            if (email.equals("LIST")) {
                for (String i : address) {
                    System.out.println(i);

                    // This is the reason that the program would get terminated 
                    // instantly if you wouldn't take user input.
                    String tempstr = scanner.next();
                    exit();
                }
            }
        }
    }
}

此改进使用exit()方法终止Java程序。

相关问题