Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Basic I/O problems in Java

i am a total newbie at java. This code i wrote checks if an integer is an odd or even number. I ran into problems when i typed in a letter, error was basically it was expecting an integer, nothing else. My question is, how do i check if the input is a valid integer and nothing else before assigning i the value of inputChar?

Thanks

import java.util.Scanner;
class Oddeven {
public static void main(String[] arguments) {

  System.out.println("Type in any integer");
  Scanner inputChar = new Scanner(System.in);

  int i = inputChar.nextInt();

  if (i != 0) {
    if (i % 2 == 0) 
      System.out.println(i + " is even");
      else {
      System.out.println (i + " is odd") ;
      }
      }
   else {
   System.out.println("Zeros are not allowed, bye!");
   }
  }
 }
like image 810
user3330990 Avatar asked Sep 26 '26 19:09

user3330990


1 Answers

You should use

inputChar.hasNextInt()

and if this function return true then it means that the next input is an integer. If it returns false then that input is not an integer. You can use it in this way.

if(inputChar.hasNextInt())
{
 if (i != 0) {
      if (i % 2 == 0) 
      System.out.println(i + " is even");
      else {
      System.out.println (i + " is odd") ;
      }
      }
   else {
      System.out.println("Zeros are not allowed, bye!");
   }
}
else {
     System.out.println("Other than integer inputs are not allowed, bye!");
}
}
like image 160
AjayLohani Avatar answered Sep 29 '26 07:09

AjayLohani



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!