Java:如何询问用户是否要继续编程 [英] Java: How to ask user if he/she wants to continue program

查看:249
本文介绍了Java:如何询问用户是否要继续编程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经做到这一点,它会告诉用户的输入是素数还是素数,但现在我必须这样做,以便它会询问用户他/她是否想要检查另一个号码,等待用户输入Y或y为是,n或N为否。如果是,请重复这三个步骤。如果不是,请退出程序。对于所有其他字母,拒绝ti并要求用户仅输入y或n。

I've already made it so that it will tell whether the input from the user is a prime number or not a prime number but now I have to make it so that it will ask the user if he/she wants to check another number and wait for the user to enter "Y" or "y" as yes, "n" or "N" as no. If yes, repeat the three steps. If no, exit the program. For all other letters, reject ti and ask the user to enter only "y" or "n".

import java.util.*;  // importing package util


public class Prime
{
    public static void main (String args[])
    {
        int num,count=0;
        Scanner scan = new Scanner(System.in); //scanner for input
        System.out.print("Enter any number : ");
        num = scan.nextInt();
        for(int i=2; i <= (num/2); i++) 
        {
            if((num % i) == 0)
            {
                count++;
                break;
            }
        }
        if((count==0) && (num!= 1))
        System.out.println( num + " is a prime number.");
        else
        System.out.println( num + " is not a prime number.");
    }
}


推荐答案

这这是我开始编码时学到的非常标准的方法。

This is a pretty standard way I learnt when I started coding.

使用 do-while 循环如下:

do
{
 System.out.print("Enter any number : ");
        num = scan.nextInt();
        for(int i=2; i <= (num/2); i++) 
        {
            if((num % i) == 0)
            {
                count++;
                break;
            }
        }
        if((count==0) && (num!= 1))
        System.out.println( num + " is a prime number.");
        else
        System.out.println( num + " is not a prime number.");
        System.out.println("Continue(Y/N)");
        char a = scan.next();

} while(a=='Y'|| a=='y')

如果用户输入其他内容,则循环将中断。 :)

If the user enter's anything else, the loop will break. :)

这篇关于Java:如何询问用户是否要继续编程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆