gpt4 book ai didi

java - 如果用户插入整数以外的字符,程序应该再给他一次写入整数的机会

转载 作者:行者123 更新时间:2023-12-01 12:18:51 25 4
gpt4 key购买 nike

好的,我试图阻止用户输入整数以外且小于 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();


}
}

}

}

最佳答案

类似这样的事情:

    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 将被执行,因此下次 while 检查其条件时,它将停止。

关于java - 如果用户插入整数以外的字符,程序应该再给他一次写入整数的机会,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26827562/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com