0

1. The InputMismatchException.
Write a program that prompts the user to read an integer and displays whether the number is even or odd. If you enter an invalid integer (for example, 2.5 is not a valid integer) your program should say so. Note, you will need the following import statement:

import java.util.InputMismatchException;

I have started the code but am struggling to get things moving. This is my first programming class so apologize for noobish errors =(

import java.util.InputMismatchException;
import java.util.Scanner;
public class Lab14 {
	public static int prime;
	public static void main(String[] args){
		Scanner input = new Scanner(System.in);
		
		while (true) {
			System.out.print("Please enter a number: ");
			if(input.hasNextInt()){
				int prime = input.nextInt();
				break;
			}
			else{
				System.out.println("\nNot a number or an integer!\n");
				input.next(); 
			}
	}
2
Contributors
2
Replies
3
Views
6 Years
Discussion Span
Last Post by javaAddict
0

err sorry messed up copy/paste

import java.util.InputMismatchException;
import java.util.Scanner;
public class Lab14 {
	public static int prime;
	public static void main(String[] args){
		Scanner input = new Scanner(System.in);
		
		while (true) {
			System.out.print("Please enter a number: ");
			if(input.hasNextInt()){
				int prime = input.nextInt();
				break;
			}
			else{
				System.out.println("\nNot a number or an integer!\n");
				input.next(); // :-)
			}
	}
		
		if (prime%2==0){
			System.out.println("The number is even!");
		}else System.out.println("The number is odd!");
	}
	

}
0

What errors do you get and where are you having problems. The code seems ok. Which part of your assignment doesn't work.
What test cases have you tried?

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.