vendredi 7 octobre 2016

how to make my allowed inputs stricter

my assignment is to write a program to check whether an input string is a valid number. a valid number being any number with or without a + or - sign and one decimal like: (+1 -1 1.0 1.0000000000 -1.0 -1.000000000) however when i put in things like: (1.2.3) it works. what am i doing wrong

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();
  }

}

Aucun commentaire:

Enregistrer un commentaire