我的任务是编写一个程序来检查输入字符串是否是有效数字。一个有效的数字是任何具有或不具有+或 - 符号和一个小数的数字,如:(+1 -1 1.0 1.0000000000 -1.0 -1.000000000)但是当我放入如下东西时:(1.2.3)它有效。我在做什么错如何让我的允许输入更严格
import java.util.Scanner;
public class parseNum {
public static void main(String[] args) {
System.out.println("Please enter a number:");
Scanner input = new Scanner(System.in);
String inStr = input.nextLine();
int i;
String state = "start";
for (i=0; i<inStr.length(); i++) {
if (state.equals("start")) {
if (inStr.charAt(i) == '+' || inStr.charAt(i) == '-') {
state = "afterSign";
continue;
}
}
// i assume this is where i messed up
if(inStr.charAt(i) == ('.')){
if(inStr.charAt(i+1) >= '0' && inStr.charAt(i+1) <= '9'){
state = "accept";
continue;
}
else{
state = "reject";
break;
}
}
if (inStr.charAt(i) >= '0' && inStr.charAt(i) <= '9') {
state = "accept";
continue;
}
else {
state = "reject";
break;
}
}
if (state.equals("accept"))
System.out.println("Thank you");
else
System.out.println("Invalid input");
input.close();
}
}
YES !!!那工作非常感谢 –
见http://stackoverflow.com/help/someone-answers – c0der