虽然循环不会停止循环异常

时间:2013-11-04 14:03:15

标签: java exception while-loop

可能错过了一些非常愚蠢的东西,但我的while循环不会停止打印错误消息。

有人可以快速查看并指出我正确的方向吗?

package week5;

import java.util.*;
public class Week5 {       
    public static void main(String[] args) {    
        Scanner myKeyboard = new Scanner(System.in);        
        inputInt();        
    }

    public static int inputInt(){        
        Scanner myKeyboard = new Scanner(System.in);        
        System.out.println("Enter number:");        
        int num;                                
        boolean carryOn = true;                       
        while (carryOn = true) {                 
                {                                    
                  try {                       
                      num = myKeyboard.nextInt();                      
                      carryOn = false;                                                                  
                      }                  
                  catch (Exception e) {
                    System.out.println ("Integers only");                                         
                   }                       
                  }                                                    
          }
        return 0;
      }

3 个答案:

答案 0 :(得分:5)

这一行是问题

    while (carryOn = true) {

您使用的是赋值运算符==,而不是使用比较运算符=。基本上,你每次迭代都要设置carryOntrue,然后自动运行循环体,因为条件基本上变为

    while (true) {

只需将问题行更改为

即可
    while (carryOn == true) {

答案 1 :(得分:1)

除了无限循环以外,无论用户输入什么类型,总是return 0;这一事实,代码远比它需要的复杂得多。

// only create one scanner
private static final Scanner myKeyboard = new Scanner(System.in); 

public static void main(String[] args) {
    int num = inputInt();
    // do something with num
}

public static int inputInt() {
    System.out.println("Enter number:");

    while (true) { 
        if (myKeyboard.hasNextInt()) {
            int num = myKeyboard.nextInt();
            myKeyboard.nextLine(); // discard the rest of the line.
            return num;
        }
        System.out.println ("Integers only, please try again"); 
    }
}

答案 2 :(得分:0)

在你的情况下:

     while(carryOn==true) 

     while(carryOn) 

将解决您的问题

相关问题