Destro77
Destro77

Reputation: 125

While loop wont stop looping with exception

probably missing something really silly, but my while loop will not stop printing the error message.

Could someone have a quick look and point me in the right direction?

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;
      }

Upvotes: 1

Views: 139

Answers (3)

Peter Lawrey
Peter Lawrey

Reputation: 533472

Apart from the infinite loop and the fact you always return 0; no matter what the user types, the code is far more complex than it needs to be.

// 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"); 
    }
}

Upvotes: 1

Shoaib Chikate
Shoaib Chikate

Reputation: 8975

In your case:

     while(carryOn==true) 

or

     while(carryOn) 

will solve your problem

Upvotes: 0

Kon
Kon

Reputation: 10810

This line is the problem

    while (carryOn = true) {

Instead of using the comparison operator ==, you are using the assignment operator =. So essentially, you're setting carryOn to true every iteration, then automatically running the body of the loop since the condition essentially becomes

    while (true) {

Just change that problem line to

    while (carryOn == true) {

Upvotes: 5

Related Questions