我试图为我的问题找到一个解决办法,但在实践中却找不到一个有效的解决办法。所以请,如果你不确定你知道解决方案是什么,不要回答。我真的需要具体的帮助。
问题是,当我运行我的简单代码-你可以选择一个数字,这很好,循环工作良好。当您选择0,它也工作(运行结束),但当你放一个字母或任何字符串-有一个问题.一个异常不停地循环,即使我尝试输入另一个值。
PS。我需要在这里使用扫描仪,所以请不要写关于读者等-如何解决这个具体的问题。
干杯,
下面是代码(只有main):
public static void main(String[] args) {
// TODO code application logic here
Scanner sc = new Scanner(System.in);
int dane = -1 ;
boolean keepLooping; //if you delete this works the same with same problem
do
{
keepLooping = false;
try
{
System.out.println("Pick a number:");
dane = sc.nextInt();
}catch (InputMismatchException e)
{
System.out.println("Your exception is: " + e);
keepLooping = false;
}
System.out.println("Out from exception");
}while ((dane != 0)||(keepLooping == true));
}发布于 2014-02-20 08:10:54
试试这个:
public static void main(String[] args) {
// TODO code application logic here
Scanner sc = new Scanner(System.in);
int dane = -1 ;
boolean keepLooping = true; //if you delete this works the same with same problem
while(keepLooping && dane != 0)
{
System.out.println("Pick a number:");
try
{
dane = Integer.parseInt(sc.next());
}catch (NumberFormatException e)
{
keepLooping = true;
}
System.out.println("Out from exception");
}发布于 2014-02-20 08:09:39
编辑的
就像这样
public static void main(String[] args) {
// TODO code application logic here
Scanner sc = new Scanner(System.in);
int dane = -1 ;
boolean keepLooping; //if you delete this works the same with same problem
do
{
keepLooping = false;
try
{
System.out.println("Pick a number:");
dane = sc.nextInt();
}catch (InputMismatchException e)
{
System.out.println("Your exception is: " + e);
keepLooping = false;
dane = sc.nextInt();
}
System.out.println("Out from exception");
}while ((dane != 0)||(keepLooping == true)&&(dane!=0));
}发布于 2014-02-20 08:12:46
问题是当你说-
dane = sc.nextInt();
在上面的行中,如果您提供了一个数字以外的任何输入,它将抛出异常输入不匹配。让我们理解这一行的作用。实际上有两件事-
首先,sc.nextInt()读取一个整数,并且只有在此任务成功完成后,它才会将该整数值赋值给变量dane。但是在读取整数时,它会抛出一个InputMismatchException,这样赋值就不会发生,然而dane有它的previos值,而不是扫描器读取的新值,所以dane仍然不等于0。循环还在继续。
希望能帮上忙。
https://stackoverflow.com/questions/21901665
复制相似问题