我的任务是编写一个程序来检查输入字符串是否是有效数字。一个有效的数字是任何数字,有或没有+或 - 符号和一个小数,如:(+ 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();
}
}
答案 0 :(得分:0)
在你的for循环之上声明一个int来计算点数,
int dotCount = 0;
接下来,每次找到一个点时计数
if(inStr.charAt(i) == ('.')){
dotCount++; //THIS LINE
if(inStr.charAt(i+1) >= '0' && inStr.charAt(i+1) <= '9'){
state = "accept";
continue;
}
else{
state = "reject";
break;
}
}
最后,添加if语句,如果它找到多于1,则拒绝。
if(dotCount > 1) {
state = "reject";
break;
}
答案 1 :(得分:0)
见评论:
import java.util.Scanner;
public class ParseNum {//use java naming conventions
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 =0;
String state = "start";
int dotCount = 0;
//check for +/- outside the loop. It should only be
//at the beginning. This will cause number with multiple
//+/- signs to fail
if (inStr.charAt(0) == '+' || inStr.charAt(0) == '-') {
state = "afterSign";
i=1;
}
for (i=0; i<inStr.length(); i++) {
if(inStr.charAt(i) == ('.')){
if(dotCount == 0){
state = "accept";
dotCount++;
continue;
}
else{//multiple dots fond
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();
}
}
请注意,具有多个0的数字(如+000009.8)被视为有效。
更简单和更好的实施方式是:
public static void main(String[] args) {
System.out.println("Please enter a number:");
Scanner input = new Scanner(System.in);
String inStr = input.nextLine();
String state = "start";
try {
Double d = Double.valueOf(inStr);
state = "accept";
} catch (NumberFormatException ex) {
state = "reject";
}
if (state.equals("accept")) {
System.out.println("Thank you");
} else {
System.out.println("Invalid input");
}
input.close();
}