How to end a while Loop via user input

前端 未结 5 367
深忆病人
深忆病人 2021-01-22 18:42
package cst150zzhw4_worst;

import java.util.Scanner;

public class CST150zzHW4_worst {

    public static void main(String[] args) {
    //Initialize Variables
    doub         


        
相关标签:
5条回答
  • 2021-01-22 18:56

    You just need to set repeat to true or false based on user input. So in the end, compare input with yes or no. Something like this would work for you :

    if ("yes".equals(input)) 
     repeat = true; // This would continue the loop
    else 
     repeat = false; // This would break the infinite while loop 
    
    0 讨论(0)
  • 2021-01-22 18:58
        boolean repeat = true;
    
       // Create a Scanner object for keyboard input.
         Scanner keyboard = new Scanner(System.in);
    
        while (repeat)
        {   
           -----------------------
           -------------------------
           System.out.println("Do you want to continue:");
           repeat = keyboard.nextBoolean();
        }
    
    0 讨论(0)
  • 2021-01-22 19:02

    You can use a break statement to exit a while loop.

    while (...) {
    
       input = ...;
       if (input.equals("Y")) {
         break;
       }
    }
    
    0 讨论(0)
  • 2021-01-22 19:09

    you also if you want your code to be more systematic , go and search about the interrupt , specially thread interrupt , these answers above is correct , find the more organic code and implement it

    0 讨论(0)
  • 2021-01-22 19:13

    You have to assign repeat in your while-loop so it becomes false if the user says yes:

    repeat = !input.equalsIgnoreCase("yes"); 
    
    0 讨论(0)
提交回复
热议问题