Search code examples
javaasciicounter

ascii table counter with Java not returning null as false


I try to validate if the user has input a number 0-9 or if it has a decimal. It does validate if it is a number or a letter but if the user doesn't put anything the loop still runs as if it is a valid number.

So, there are two bugs:

  1. User hits enter before inputting a valid floating point number and the script still runs as valid.

  2. User enters a period without entering any numbers and the script still runs as valid.

package numbers;

import java.util.Scanner;

public class IsAValidNumber
{
    public static void main(String[] args)
    {
        //console input scanner
        Scanner consoleInput = new Scanner(System.in);
        
        //Prompt user for input
        System.out.print("enter a valid number:");
        String validat = consoleInput.nextLine();

        boolean isTrue = NumberIsValid(validat);
        while(isTrue == true)
        {
            System.out.println(validat + " is a valid number. Please enter another value:");
            validat = consoleInput.nextLine();
            isTrue = NumberIsValid(validat);
        }
        //if it jumps out of the while because it is false run this
        System.out.println(validat + " is not a valid number, bye");
        consoleInput.close();
    }
    
    public static boolean NumberIsValid(String value)
    {
        int period = 0;
        boolean valid = true;
        int length = value.length();
        
        //run through the string
        //check the numbers
        for(int i = 0; i < length; i++)
        {
            char aChar = value.charAt(i);
            // make sure it doesn't start with a space
            if((int)aChar == 20)
            {
                valid =false;
                break;
            }
            
            // check to make sure its is a int 0-9
            else if((int)aChar < 48 || (int)aChar > 57)
            {
                if((int)aChar == 46)
                {
                    period++;
                }
                else
                {
                    valid = false;
                    break;
                }
                
            }

            //make sure it doesn't have more than one period
            if (period > 1)
            {   
                valid = false;
                break;
            }
        }

        return valid;
    }
}

How can I do this correctly?


Solution

  • For bug #1: in your method NumberIsValid(String value), you never check if the argument is empty or not. When an empty argument is passed to your method, the for loop is skipped and it returns true.

    For bug #2: Not the best solution, but you could simply create something like this:

        if (value.contains(".") && length == 1) {
            return false
        }