可以使用正则表达式来检查输入是否是整数或非整数。下面是一个示例代码:
import java.util.Scanner; import java.util.regex.Pattern;
public class Main { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.print("请输入一个整数或非整数:"); String userInput = input.nextLine();
Pattern integerPattern = Pattern.compile("^-?\\d+$"); //整数的正则表达式
Pattern nonIntegerPattern = Pattern.compile("^-?\\d+\\.\\d+$"); //非整数的正则表达式
if (integerPattern.matcher(userInput).matches()) { //匹配整数的正则表达式
int userInt = Integer.parseInt(userInput);
System.out.println(userInt);
} else if (nonIntegerPattern.matcher(userInput).matches()) { //匹配非整数的正则表达式
double userDouble = Double.parseDouble(userInput);
System.out.println(userDouble);
} else {
System.out.println("输入不是整数或非整数。");
}
}
}