我是java的新手。我编写的这段代码检查整数是奇数还是偶数。当我输入一个字母时,我遇到了问题,错误基本上是期待一个整数,没有别的。我的问题是,在分配输入值的值之前,如何检查输入是否是有效整数?
由于
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!");
}
}
}
答案 0 :(得分:2)
你应该使用
<强> inputChar.hasNextInt()强>
如果此函数返回true,则表示下一个输入是整数。如果返回false,则该输入不是整数。你可以这样使用它。
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!");
}
}
答案 1 :(得分:1)
您可以在调用try-catch
时添加inputChar.nextInt();
块,如果抛出异常则打印“非数字”(如果用户键入字母就是这种情况)。
试试这个:
int i = 0;
try
{
i = inputChar.nextInt();
}
catch (InputMismatchException e)
{
System.out.println("Not a number");
}
答案 2 :(得分:1)
使用hasNextInt()验证来自扫描仪的输入。
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;
if(!inputChar.hasNextInt())
System.out.println("Not a number");
else{
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!");
}
}
}
}
答案 3 :(得分:1)
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);
while (true) {
Integer i=0;
Object test = inputChar.next();
if(test instanceof Integer)
{
i=(Integer)test;
if (i == 0) {
System.out.println("Zeros are not allowed, try again!");
continue;
}
System.out.println(i + " is " + ((i % 2 == 0) ? "even" : "odd"));
}
else{
System.out.println("Please Enter An integer");
}
}
}
答案 4 :(得分:1)
好的,这是我的解决方案,无限循环在用户输入0或终止程序时中断:
import java.util.Scanner;
class Oddeven {
public static void main(String[] arguments) {
Scanner inputChar = new Scanner(System.in);
int i;
while (true) {
System.out.println("Type in any integer:");
if(!inputChar.hasNextInt()) {
System.out.println("Not a number");
inputChar.next();
} else {
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!");
break;
}
}
}
}
}
询问你是否理解某些东西,希望它有所帮助,欢呼!