Java 方法,该方法返回整数或字符串
我必须从控制台读取菜单选项,选项可以是整数或字符串。我的问题是,是否有另一种方法来检查输入是string还是intJava 方法,该方法返回整数或字符串,java,Java,我必须从控制台读取菜单选项,选项可以是整数或字符串。我的问题是,是否有另一种方法来检查输入是string还是int import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class Read { public Object read(){ String option = null; BufferedRe
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Read {
public Object read(){
String option = null;
BufferedReader buffer = new BufferedReader(new InputStreamReader(System.in));
try {
option = buffer.readLine();
if(isInt(option)){
return Integer.parseInt(option);
} else if(isString(option)){
return option;
}
} catch (IOException e) {
System.out.println("IOException " +e.getMessage());
}
return null;
}
private boolean isString(String input){
int choice = Integer.parseInt(input);
if(choice >= 0){
return false;
}
return true;
}
private boolean isInt(String input){
int choice = Integer.parseInt(input);
if(choice >= 0){
return true;
}
return false;
}
}
像这样的
boolean b = true:
try
{
int a = Integer.parseInt(input);
}
catch(NumberFormatException ex)
{
b = false;
}
如果它不是整数,b
将为false,或者保持true
类似这样的值
boolean b = true:
try
{
int a = Integer.parseInt(input);
}
catch(NumberFormatException ex)
{
b = false;
}
如果它不是整数
b
将为false或保持true
您可以使用regex,则该方法如下所示:
private boolean isInt(String input){
return input.matches("\\d+");
}
然后检查它:
if (isInt(option)){
return Integer.parseInt(option);
} else {
return option;
}
您可以使用regex,然后该方法如下所示:
private boolean isInt(String input){
return input.matches("\\d+");
}
然后检查它:
if (isInt(option)){
return Integer.parseInt(option);
} else {
return option;
}
这取决于你所说的“整数”是什么意思 如果您的意思是“一个整数”,最简单和最好的方法是使用正则表达式:
private boolean isInt(String input){
return input.matches("\\d+");
}
如果您的意思是“javaint
”,则必须尝试对其进行解析,并将异常视为证明它不是有效的int
:
private boolean isInt(String input){
try {
Integer.parseInt(input);
return true;
} catch (NumberFormatException ignore) {
return false;
}
}
这取决于你所说的“整数”是什么意思 如果您的意思是“一个整数”,最简单和最好的方法是使用正则表达式:
private boolean isInt(String input){
return input.matches("\\d+");
}
如果您的意思是“javaint
”,则必须尝试对其进行解析,并将异常视为证明它不是有效的int
:
private boolean isInt(String input){
try {
Integer.parseInt(input);
return true;
} catch (NumberFormatException ignore) {
return false;
}
}
@波希米亚人:是的,它节省了包装和拆开包装,不仅如此,它还意味着它不能为
null
;布尔值只有两个可能的值,但布尔值有三个。@Bohemian是的,它可以保存包装和展开,不仅仅是这样-它意味着它不能为null
;布尔值只有两个可能值,但布尔值有三个。