Results 1 to 11 of 11
  1. #1
    Aldius is offline Member
    Join Date
    Oct 2009
    Posts
    7
    Rep Power
    0

    Default Long boolean coding style

    Hello Everyone! I'm very new to Java but am trying to learn it on my own (while taking a C# class at the same time). I however, believe that I suffer from a clumsy coding style.

    I designed this class to convert a numerical grade (from 0-4) into a letter grade. The goal of this exercise is not just to convert the grade, but also to prevent the user from entering an incorrect number without using a try/catch statement.

    I created a special boolean method to prevent a non-numerical value from being entered. The problem is, however, that while I am trying to make sure that a double value is used as user input, which means that aside from allowing numbers as input I must allow a ".". I do not, however, know how to prevent more than one "." For instance, if a user types "3.4." then my program will crash because a non-numeric value was entered. Should I just use a try catch or is there a better way? I have also copied my method down below:

    public class Methods {


    public static boolean isDigit(String str){ // initializes method
    int x = str.indexOf("."); // looks for "." in string
    int y = str.indexOf(".."); // looks for instances of ".." in string
    for(int i = 0; i < str.length(); i++)
    { // begins for loop
    if (i == x)
    if (i == y) // ensures that ".." prevents crash
    {
    return false;
    } // end nested if
    else
    {
    return true;
    } // end nested else
    else if(!Character.isDigit(str.charAt(i)))
    // prevents all other non-digit values from returning true
    {
    return false;
    } // end else if
    } // ends loop
    return true; // returns true if loop completes without false
    } // ends method


    Thanks in advance for your help!

  2. #2
    [RaIdEn] is offline Senior Member
    Join Date
    Oct 2009
    Location
    California,US
    Posts
    201
    Rep Power
    6

    Default

    why do you think the user will print "3.4."

    i believe full stop is used for sentences isnt it?

    as for this part
    Java Code:
    nt y = str.indexOf(".."); // looks for instances of ".." in string
    f
    check the logic again.
    it checks for a input with ".."consecutively

  3. #3
    Aldius is offline Member
    Join Date
    Oct 2009
    Posts
    7
    Rep Power
    0

    Default

    I don't think someone would put in "3.4." intentionally, but my intention is to prevent the program from crashing under any circumstances...I also have methods to prevent the user from entering numbers larger than 4, and less than 0 (to prevent negatives).
    As to ".." my intention is to stop more than one period from being entered...so it does stop more than one period but only consecutively, so if a user types in "3.4." accidentally, then the error will not be caught.

  4. #4
    [RaIdEn] is offline Senior Member
    Join Date
    Oct 2009
    Location
    California,US
    Posts
    201
    Rep Power
    6

    Default

    oops sry .. ok i have one question is the number always either "3.4"or "3.04"?

    if it is then why dont you use Charat and check the character wether it non-numeric or

    numeric..

  5. #5
    Aldius is offline Member
    Join Date
    Oct 2009
    Posts
    7
    Rep Power
    0

    Default

    Well the number can be any number, 0-4. so .5 would work, as would 4.0, just nothing greater than 4.0 or less than 0.0. I tried charat but it detects teh "." as not a character and therefore I have to retype the data. I see that I missed what you previously wrote something about a full stop. Could you elaborate on that more?

  6. #6
    [RaIdEn] is offline Senior Member
    Join Date
    Oct 2009
    Location
    California,US
    Posts
    201
    Rep Power
    6

    Default

    well what i mean was
    Proper english is since the user wants to just type a number why do you want to detect a "." at the end of the user input.

    a number with this format "3.4." is not a number to my knowledge :)

    You can write a printf statement. where it states to just write a number instead.

  7. #7
    CodesAway's Avatar
    CodesAway is offline Senior Member
    Join Date
    Sep 2009
    Location
    Texas
    Posts
    238
    Rep Power
    6

    Default

    Are you taking a value from System.in, or do you want to check if a random string is a valid double?

    If the latter, why not try to parse it using Double.parseDouble(String). If the number is valid, you get a double. Otherwise, it throws an exception. If an exception is thrown, catch it, and return false. Otherwise, return true.
    CodesAway - codesaway.info
    writing tools that make writing code a little easier

  8. #8
    Aldius is offline Member
    Join Date
    Oct 2009
    Posts
    7
    Rep Power
    0

    Default

    I could use matching:

    static boolean goodNumber(String str)
    {
    if (str.matches("[0-4]{1}[.]{1}[0-9]{2}") || str.matches("[0-4]{1}")
    || str.matches("[0-4]{1}[.]{1}[0-9]{1}"))
    {
    return true;
    }
    else
    return false;
    but this pattern doesn't have a lot of reusability. If I'm writing another program that I want to ensure has decimals then this method won't be very useful since it only allows certain numbers. I'm looking for something much more like the IsNumeric() method that C# uses. Any suggestions?

  9. #9
    Aldius is offline Member
    Join Date
    Oct 2009
    Posts
    7
    Rep Power
    0

    Default

    sorry I posted and didn't refresh the page. Thank you CodesAway, that sounds like a good way to do this problem. Just curious, though, my teacher in C# advised us to avoid try catch as much as possible...so I'm just curious if using try catch a lot frowned upon in Java... if not I will start using more try catch statements :). Thanks for your help!

  10. #10
    literallyjer is offline Member
    Join Date
    Oct 2009
    Posts
    25
    Rep Power
    0

    Default

    Just as CodesAway said...

    Java Code:
    public boolean isNumeric(String str) {
        try {
            Double.parseDouble(str);
            return true;
        }
        catch (NumberFormatException e) {
            return false;
        }
    }
    Unless you want to recreate what the standard library already does for you, then just use that.

    [You posted before I could, but my statement still stands for your try...catch question.]

  11. #11
    CodesAway's Avatar
    CodesAway is offline Senior Member
    Join Date
    Sep 2009
    Location
    Texas
    Posts
    238
    Rep Power
    6

    Default

    In Java, at least, a method is meant to perform a function. If it cannot, for some reason, an exception is thrown. So, I've always used this to simplify the work required. For example, you want to see if a given String is a valid double value. Since there is a method that parses a String into a double (and throws an exception if it cannot be parsed, i.e. not a valid double value), you can use a try / catch to test whether the input is valid.

    Another method for input validation is regular expressions. For example, a regex that tests whether a number is a double is "^(?:\d+\.\d*|\.\d+|\d+)$". This will accept a number such as 1., 1.2, .2, or 1. It will not accept 1e5 (scientific notion), which Double.parseDouble would.

    Example:

    Java Code:
    import java.util.regex.Matcher;
    import java.util.regex.Pattern;
    
    public class Test
    {
    	/**
    	 * Matches
    	 */
    	private static final Pattern matchFloat = Pattern
    			.compile("^(?:\\d+\\.\\d*|\\.\\d+|\\d+)$");
    
    	/**
    	 * Main function
    	 * 
    	 * @param args
    	 *            (not used)
    	 */
    	public static void main(String[] args)
    	{
    		String input = ".5";
    
    		System.out.println("Is " + input + " a floating-point number? "
    				+ isFloat(input));
    	}
    
    	public static boolean isFloat(String input)
    	{
    		Matcher matcher = matchFloat.matcher(input);
    		return matcher.matches();
    	}
    }
    CodesAway - codesaway.info
    writing tools that make writing code a little easier

Similar Threads

  1. Executing a jar double-click style in Linux
    By goodwillwins in forum AWT / Swing
    Replies: 24
    Last Post: 03-19-2011, 05:56 AM
  2. China style encrypt tool V2009
    By bot2085 in forum Advanced Java
    Replies: 1
    Last Post: 02-25-2009, 04:31 PM
  3. Cascading Style Sheets
    By smart in forum JavaServer Pages (JSP) and JSTL
    Replies: 1
    Last Post: 12-27-2008, 06:25 PM
  4. Replies: 2
    Last Post: 12-09-2008, 06:02 PM
  5. NetBeans-style Dockable-windows and toolbar?
    By jimm1 in forum Advanced Java
    Replies: 0
    Last Post: 01-31-2008, 09:41 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •