Link to home
Create AccountLog in
Avatar of SunnyX
SunnyX

asked on

core java. isInteger methods. Finding bug.

public static int isInputInteger(){
		@SuppressWarnings("resource")
		Scanner input = new Scanner(System.in);   

		int correctNumber;
		
			while(true){   
			input.nextLine();
				    if(input.hasNextInt()){   
				    	correctNumber = input.nextInt();
				        break;
				    }
				    else{
				    	System.out.println("Your input isn't integer.Please, try again. ");
				    }
			}
			return correctNumber;
			}

Open in new window


class PrintFromInput {

	protected static int  printNumber() {
    	System.out.printf("Please, enter integer: ");
    	int intYourConsoleInput = Assert.isInputInteger();
         return intYourConsoleInput; 
    }
}

public class Task {
    public static void main(String[] args) {
    	
    	System.out.println("Congratulation! Your correct integer input is: "+ PrintFromInput.printNumber()); 
    	
    }
}

Open in new window


Inside class Assert there is a method "isInputInteger" everything work but not as I expect :
Session 1
input : f
output: {nothing }
input : f
output : Your input isn't integer.Please, try again.
input: g
output : Your input isn't integer.Please, try again.
input : 3
Congratulation! Your correct integer input is: 3
Session OVER
My question is why there isn't any message after first "f". Please, help me to find bug. Thx in advance !
Avatar of krakatoa
krakatoa
Flag of United Kingdom of Great Britain and Northern Ireland image

At first glance, maybe because you are advancing the scanner too early.
why don'y you try setting breakpoints and debugging to find out what going on?
Remove this line :

input.nextLine();

Open in new window

SOLUTION
Avatar of James Bilous
James Bilous
Flag of United States of America image

Link to home
membership
Create a free account to see this answer
Signing up is free and takes 30 seconds. No credit card required.
See answer
Yes, indeed.  I thought the OP would be able to work out the required code move once he sees the result of just deleting it.
SOLUTION
Link to home
membership
Create a free account to see this answer
Signing up is free and takes 30 seconds. No credit card required.
ASKER CERTIFIED SOLUTION
Link to home
membership
Create a free account to see this answer
Signing up is free and takes 30 seconds. No credit card required.
Avatar of SunnyX
SunnyX

ASKER

The solution is :
public static int onlyIntegerInput(){
		@SuppressWarnings("resource")
		Scanner scanner = new Scanner(System.in);   

		int correctNumber;
		
		while (true){

			if(!(scanner.hasNextInt())){
				System.out.println("Your input isn't integer. Please, try again. ");
				scanner.next();
				continue;
				}
			else{
			correctNumber = scanner.nextInt();
			break;
			}
		}
			return correctNumber;
	}

Open in new window



Dear experts thx you so much for your help !
Avatar of SunnyX

ASKER

Everybody many thanks !
Yes, that's it.