我正在尝试打印无效数字,该数字不是 int
或 double
类型,但没有获得所需的输出,请帮助我指出我的错误,另一件事是可以使用其他方式找出无效数字吗?
public class Test {
public static void main(String [] args)
{
String [] str ={ "10.20","30450","12.valid","100.200"};
for(int i=0; i<str.length; i++)
{
if(str[i].indexOf(".")>0)
{
try
{
Integer.parseInt(str[i]);
System.out.println("its a valid int nummber : "+str[i]);
}
catch(NumberFormatException e)
{
System.out.println("its invalid number in string: "+str[i]);
}
}
else
{
try
{
Double.parseDouble(str[i]);
System.out.println("its valid double number: "+str[i]);
}
catch(NumberFormatException e)
{
System.out.println("its invalid char in string : "+str[i]);
}
}
}
}
}
输出
its invalid number is string: 10.20
its valid double number: 30450
its invalid number is string: 12.valid
its invalid number is string: 100.200
最佳答案
if/else 中的代码应该是相反的:
if(str[i].indexOf(".")>0)
{
///parse for double
}
else
{
//parse for int
}
关于java - 在 Java 中打印字符串中的无效输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30891211/