brl*_*214 0 java integer println
程序告诉用户输入的整数是零,正,偶数还是奇数,还是负数,偶数或奇数.
我的问题是如果输入非整数,我想在println中添加错误.看最后一行.
import java.util.Scanner;
public class IntegerCheck {
public static void main(String [] args) {
int x;
System.out.println("Enter an integer value:");
Scanner in = new Scanner(System.in);
x = in.nextInt();
//String x = in.nextInt();
if (((x % 2) == 0) && (x< 0))
System.out.println(x + " is a negative, even integer.");
else if (((x % 2) == 0) && (x == 0))
System.out.println(x + " is Zero.");
else if ((x % 2)==0)
System.out.println(x + " is a positive, even integer.");
if (((x % 2) != 0) && (x<0))
System.out.println(x + " is a negative, odd integer.");
else if ((x % 2) != 0)
System.out.println(x + " is a positive, odd integer.");
if (x != 'number')
System.out.println(x + " is not an integer.");
}
}
Run Code Online (Sandbox Code Playgroud)
你可以使用InputMismatchException抛出的Scanner.nextInt().将代码包含在try/ catchblock中并捕获一个InputMismatchException.它看起来像 -
try{
x = in.nextInt();
if (((x % 2) == 0) && (x< 0))
System.out.println(x + " is a negative, even integer.");
else if (((x % 2) == 0) && (x == 0))
System.out.println(x + " is Zero.");
else if ((x % 2)==0)
System.out.println(x + " is a positive, even integer.");
if (((x % 2) != 0) && (x<0))
System.out.println(x + " is a negative, odd integer.");
else if ((x % 2) != 0)
System.out.println(x + " is a positive, odd integer.");
}
catch(InputMismatchException e){
System.out.println("You did not enter an integer!");
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1085 次 |
| 最近记录: |