Java-您要继续吗?(是/否)

时间:2018-09-01 16:19:53

标签: java loops repeat continue

我想为程序编写一个简单的循环以返回并重新启动它。

一个简单的1问题程序。然后系统询问用户是否要再次执行此操作。如果用户输入Y ...,则程序会将其循环回到开头并再次运行整个程序。如果用户输入N,则退出。

import java.util.Scanner; // show them as code

public class HowToDoLoop {

public static void main(String[] args) {

    Scanner input = new Scanner(System.in);

    System.out.print("How much money do you want to have? ");
    double money = input.nextDouble();

    System.out.println("Ok, here is yours $" + money);

    System.out.println("Do you want to continue y or n");

2 个答案:

答案 0 :(得分:1)

while(true){

    System.out.println("How much money do you want to have? ");
    double money = input.nextDouble();

    System.out.println("Ok, here is yours $" + money);

    System.out.println("Do you want to continue y or n");
    String c = input.nextLine();

   if(c.equalsIgnoreCase("n")){ 
      break;
     }//else continue to loop on any string ;-)

}

答案 1 :(得分:1)

String c = "";
do{
    System.out.println("How much money do you want to have? ");
    double money = input.nextDouble();

    System.out.println("Ok, here is yours $" + money);

    System.out.println("Do you want to continue y or n");
    c = input.nextLine();

}while(c.equalsIgnoreCase("Y"));