Java 如果用户插入的字符不是整数,程序应该给他另一个机会来写一个整数

Java 如果用户插入的字符不是整数,程序应该给他另一个机会来写一个整数,java,exception,Java,Exception,好的,我试图阻止用户输入除整数以外的小于3的值(第一种情况)。到目前为止,我有这个代码,问题是,我不能让它停止,直到用户输入正确的值。我想让他在变量n中插入一个整数,然后继续在变量a中添加一个值。我该怎么做? 编辑:新代码 public class mnohouholnik { public double a; public int n; public void main() { Scanner sc = new Scanner(System.in); boolean

好的,我试图阻止用户输入除整数以外的小于3的值(第一种情况)。到目前为止,我有这个代码,问题是,我不能让它停止,直到用户输入正确的值。我想让他在变量n中插入一个整数,然后继续在变量a中添加一个值。我该怎么做? 编辑:新代码

public class mnohouholnik  {
 public double a;
 public int n;
 public void main() {
     Scanner sc = new Scanner(System.in);
     boolean error = false;

while ( ! error && n<3 ) { //you cant have a polygon which has only two angles

    try
    {

       System.out.println("Enter the number of angles in polygon");
        n = sc.nextInt();

        error = true;




    }
    catch(InputMismatchException e )
    { 
        System.out.println("Wrong value, try again");
        sc.nextLine();


    }

    try
    {

       System.out.println("Insert the length of the side :");
        a = sc.nextDouble();
        error = true;



    }
    catch(InputMismatchException e )
    { 
        System.out.println("Wrong value, try again");
        sc.nextLine();


    }
} 
公共类mnohouholnik{
公共双a;
公共int n;
公共图书馆{
扫描仪sc=新的扫描仪(System.in);
布尔错误=假;
而(!error&&n类似这样的内容:

    boolean validInput = false;

    while ( ! validInput ) {

        try
        {

            System.out.println("Please insert a number of angles in polygon:");
            n = sc.nextInt();
            validInput = true;

        }
        catch(InputMismatchException exception )
        { 
            System.out.println("Thats not an integer");
        }
    }
首先,它假设输入无效。当输入无效时,它将重复输入过程。通知它停止的标志仅在
sc.nextInt()之后更改
调用。如果该调用引发异常,控制将传递到
catch
子句,并且
validInput
将不会更改。如果它工作正常且未引发异常,则将执行
validInput=true
,因此下次
检查其条件时,它将停止。

尝试以下操作:

    boolean valid = false;
    while(valid == false){

    //input code here 
    //if statement changing 'valid' to true, if the input is valid

    }

我试过了,但它一直在运行。只要我输入一个字母
a
,它就会写下那些句子,直到我重置它:/@MarekKošk尝试添加
sc.next()
sc.nextLine()
catch
子句中。如果出现异常,扫描器似乎没有使用该字母。现在我正在尝试添加第二个变量,即单侧的长度。仍然是相同的原则,但我被卡住了。在第一个变量不正确之前,用户不应该向下一个变量添加值,但它似乎不起作用.我真的很抱歉打扰你,但你能帮我解决这个问题吗?请编辑你的问题,并在其中添加新信息。你可以写一些类似“编辑:我的新代码是…我有这个问题:…”。如果输入正常,将
error
设置为
false
,并在
error&&n您确切想到的错误时循环,这不是更有意义吗?如果用户输入正确,则将变量
error
设置为
true
。这没有多大意义,因为变量名是
error
,而不是
>好的
validInput
就像@realpoint的答案一样)。