Home > Blockchain >  Can't quit from the loop
Can't quit from the loop

Time:02-06

I Was trying to make a small program that would take user's data, and when user would print "LIST" it would show all data and end program but it wont end

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<>();
        while (true) {

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

            }
        }
    }
}

CodePudding user response:

Your code doesn't do anything to stop the program.

One way to achieve what you want is to test against a boolean value instead of true in your while loop. You can set the boolean to false when the user enters LIST. Here I added such a variable, and named it 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;
         }
      }
   }
}

CodePudding user response:

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<>();
        while (true) {

            addres.add(email);
            
            
            if (email.equals("LIST")) {
                for (String i : addres) {
                    System.out.println(i);
                    String tempstr = scanner.next(); // This is for the reason that the program would get terminated instantly if you wouldn't take user input
                    exit();
                }

            }
        }
    }
}

This improvation uses the exit() method which terminates a java program.

  • Related