jeudi 6 octobre 2016

Make . appear only once

I am in a bit of a pickle, I am trying to make java check for values and see if they match in the ascii code (the number not letters)

Now the problem is that the . must appear only once, and for some reason my if statement does work although when I put the . at the 4th character with a combination from any other character it tell me that it's valid and crashes.

Example: input = .22. Output = is valid and crash

Other example: input = .2. Output = is not valid and java does not crash (that's good)

Here is the code:

import java.util.Scanner;

public class Program04 {
    public static void main(String[] args){

        //Declaration of various strings

        String question = "Please enter a valid (4 character) double literal: ";
        String answerWrong = " is not a valid (4 character) double literal ";
        String answerCorrect = " is a valid (4 character) double literal ";


        //Chars
        char a;
        char b;
        char c;
        char d;

        Scanner input = new Scanner(System.in);

        String nbr;


//Prompts user with question

        System.out.print(question);

        nbr = input.nextLine();



//Actual program, checks for length with if statement

        if(nbr.length() == 4){

            a = nbr.charAt(0);
            b = nbr.charAt(1);
            c = nbr.charAt(2);
            d = nbr.charAt(3);

            //Ascii code lookup

            if((a >= 48 && a<=57 || a == 43 || a == 45 || a == 46) && (b != 46 || c != 46 || d != 46)){
                if((b >= 48 && b <= 57 || b == 46) && (a != 46 || c != 46 || d != 46)){
                    if((c >= 48 && c <= 57 || c == 46) && (a != 46 || b != 46 || d != 46)){
                        if((d >= 48 && d <= 57 || d == 46) && (a != 46 || b != 46 || c != 46)){
                    System.out.println(nbr + answerCorrect);
                        }

                        else
                        {//in case the input is wrong
                            System.out.println(nbr + answerWrong);
                        }
                    }
                    else{//in case the input is wrong
                        System.out.println(nbr + answerWrong);
                    }
                }
                    else{//in case the input is wrong
                        System.out.println(nbr + answerWrong);
                    }
            }
            else{//in case the input is wrong
                System.out.println(nbr + answerWrong);
            }

            }
        else{ //in case the input is wrong
            System.out.println(nbr + answerWrong);
        }

        input.close();

    }

}

I seriously do not see the problem..........

MIND that even if I add an

else if((d == 46) && (a == 46 || b == 46 || c == 46)){
Print that input is wrong
}

Same comes out!

Aucun commentaire:

Enregistrer un commentaire