> My code is looping and crashing my program when I try to run it?

My code is looping and crashing my program when I try to run it?

Posted at: 2014-12-18 
while(isvalid == false){

System.out.println("Enter an integer");

num = kein.nextInt();

if(num % 1 == 0 ){

isvalid = true;

}

}//end of while loop

if num modulus 1 is 0 that means its an int and will exit the loop

Where do you instantiate keyIn? Your code should work with "Scanner keyIn = new Scanner(System.in);" at the top of the function. At least it does for me.

Edit: Part of the problem is that you are checking if the scanner has a nextInt even though there is no input yet... this would probably work if you have input from a file, but not from the console.

Edit:

Your function will continue to loop and print those print statements if someone enters something that is not an integer. If you use Alec's code, it will just throw an exception if someone enters something that is not an integer.

You might want to try nextLine() and parse the input in a try/catch block instead of what you have right now.

String temp = "";

int count = 0;

float sum = 0;

boolean validInt = false;

do {

System.out.println("Please enter an integer value: ");

temp = keyIn.nextLine();

try {

count = Integer.parseInt(temp);

validInt = true;

}

catch (Exception e) {

System.out.println("You have not entered a valid integer!");

}

} while (validInt == false);

Alternatively, you could use :

keyIn.nextLine();

in your else statement to throw away what is in the Scanner.

public static void sumSquared(){

int count = 0;

float sum = 0;

boolean validInt = false;



do {

System.out.println("Please enter an integer value: ");

if (keyIn.hasNextInt()){

count = keyIn.nextInt();

validInt = true;

} else {

System.out.println("You have not entered a valid integer!");

validInt = false;

}

} while (validInt == false);

System.out.println("Please enter " + count + " numbers: ");

for (int i = 1; i <= count; i++){

System.out.print(i + ": ");

Float num = keyIn.nextFloat();

sum = (sum + (num * num));

}

System.out.println("The sum of squares of those numbers are: " + sum);

}

}

Basically, I'm just trying to get the user to re-enter an integer if he didn't enter a valid one. But Jcreator keeps looping the code forever and crashes.