【问题标题】:In java how do I continue the program if the user inputs 'YES' and close it if the user inputs 'NO'?在java中,如果用户输入'YES',我如何继续程序,如果用户输入'NO'则关闭它?
【发布时间】:2017-08-07 16:25:28
【问题描述】:

您好,我正在尝试制作一个程序,当您运行该程序时,它就像您与机器人交谈,机器人会问一些关于您自己的问题,但我已经包含了一个部分,它会询问您是否愿意继续,但后来我被卡住了如果用户输入“否”,如何使程序继续运行或关闭。到目前为止,这是我所有的代码:

/********************
*Husnain Sheraz
*06/08/17
*To test knowledge
*Home
********************/




import java.util.concurrent.TimeUnit;
import java.util.Scanner;
public class reviseJava{

    public static void main(String[] args)
    throws InterruptedException {
        //Introduction just saying my name.
        printWithDelays("Hello my name is HUS9.EXE", TimeUnit.MILLISECONDS, 100);

        TimeUnit.SECONDS.sleep(2);

        //Asking user's name and printing it.

        //start a new line
        System.out.println("");

        Scanner scan = new Scanner(System.in);

        //A prompt for the user to enter his name.
        printWithDelays("What's your name?", TimeUnit.MILLISECONDS, 100);

        //reads the next letters (string) the user presses before hitting enter.
        String usersName = scan.nextLine();

        //printing out the word hello and what ever the user inputted as his/hers name.
        printWithDelays("Hello " + usersName, TimeUnit.MILLISECONDS, 100);

        TimeUnit.SECONDS.sleep(1);


        printWithDelays(" i'm going to ask you some basic questions about yourself. If you would like to continue please type 'YES' if you would not like to continue please type 'NO'.", TimeUnit.MILLISECONDS, 100);

        printWithDelays("Would you like to continue?", TimeUnit.MILLISECONDS, 100);

        String answer = scan.nextLine();

    }














public static void printWithDelays(String data, TimeUnit unit, long delay)
        throws InterruptedException {
    for (char ch:data.toCharArray()) {
        System.out.print(ch);
        unit.sleep(delay);
    }
    }

}

【问题讨论】:

  • 你需要研究 Java.Util.Scanner 类。
  • @DevelopingDeveloper 不是真的,这个问题是问如何获取输入,这个问题是关于如何根据变量的值退出,因为已经收到了输入。

标签: java


【解决方案1】:

你可以使用

System.exit(0) 

当匹配到“否”时

【讨论】:

  • @SchoolBoy 感谢你们俩,我的代码按照我的需要工作。我添加了代码行 if (answer.equals("NO")) System.exit(0);
【解决方案2】:

您可以将System.exit(0); 放在 if 语句中以结束您的程序

【讨论】:

    【解决方案3】:

    您应该使用if 语句检查该值:

    if(answer.equals("NO")){
        return;
    }
    

    如果用户输入“NO”,这将退出程序,否则继续。

    【讨论】:

    • 我回复了@Akash 评论,感谢你我做了类似的事情。
    【解决方案4】:

    让你的代码在 while 循环中运行

      public static void main(String[] args){
      Scanner scan = new Scanner(System.in);
        String input="";
    
        While(!(input=scan.nextLine()).equals("NO")){
    
        // your code goes here
        System.out.println("input not NO");
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2016-11-03
      • 2020-05-24
      • 2022-11-11
      • 1970-01-01
      • 2023-04-10
      • 2023-02-23
      • 2022-01-12
      • 2021-08-07
      • 2014-04-18
      相关资源
      最近更新 更多