Results 1 to 9 of 9
  1. #1
    Join Date
    Mar 2016
    Posts
    93
    Rep Power
    0

    Default Cannot invoke length() on the primitive type double

    I'm supposed to modify the getDouble method in the following code, so that it removes any $ or % signs from the string that's entered by the user, but I'm having problems getting the program to convert the double into a string:
    Java Code:
    public static double getDouble(String prompt) {
            double d = 0;
            while (true) {
                System.out.print(prompt);
                try {
                    d = Double.parseDouble(sc.nextLine());
                    String dude = d.toString();//Cannot invoke toString() on the primitive type double
                    for(int i = 0; i < d.length(); i++){//Cannot invoke length() on the primitive type double
            			if((d.charAt(i) == '$') || (d.charAt(i) == '%')){
            				d.deleteCharAt(i);
            				i--;//Deleting the dash character with the deleteCharAt method causes all characters
            				//to the right of that deleted dash to move forward one index. That's we we need to
            				//decrement the counter, so that the loop doesn't skip any characters.
            			}
            		}
                    break;
                } catch (NumberFormatException e) {
                    System.out.println("Error! Invalid decimal. Try again.");
                }
            }
            return d;
        }

  2. #2
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    20,003
    Rep Power
    33

    Default Re: Cannot invoke length() on the primitive type double

    having problems getting the program to convert the double into a string:
    please explain. If you are getting errors, copy the full text of the error message and paste it here.

    Can you explain what the method is supposed to do with the String arg that is passed to it: prompt

    Why is there a while(true) loop in the method?

    Note: primitives do not have methods. methods belong to classes.

    This method looks like it was written without any work on a design for it. I don't know where to begin in trying to fix it.
    I suggest that you start over. Write down the steps the method should take and work on them one at a time. Write the steps to take as comments in the code and then code, compile and execute it. Fixing any errors before moving to the next step.
    If you don't understand my response, don't ignore it, ask a question.

  3. #3
    Join Date
    Mar 2016
    Posts
    93
    Rep Power
    0

    Default Re: Cannot invoke length() on the primitive type double

    Quote Originally Posted by Norm View Post
    please explain. If you are getting errors, copy the full text of the error message and paste it here.
    Here is the original, end-of-chapter-excercise-starter getDouble method, before the for loop and any other modifications I made to it:
    Java Code:
    public static double getDouble(String prompt) {
            double d = 0;
            while (true) {
                System.out.print(prompt);
                try {
                    d = Double.parseDouble(sc.nextLine());                
                    break;
                } catch (NumberFormatException e) {
                    System.out.println("Error! Invalid decimal. Try again.");
                }
            }
            return d;
        }
    And here is the full code for the java file (Main.java) with the main method, where the getDouble method is called on lines 13 and 15:
    Java Code:
    public class Main {
    
        public static void main(String[] args) {
            // displayLine a welcome message
            Console.displayLine("Welcome to the Future Value Calculator");
            Console.displayLine();
    
            String choice = "y";
            while (choice.equalsIgnoreCase("y")) {
    
                // get input from user
                double monthlyInvestment = 
                        Console.getDouble("Enter monthly investment:   ");
                double yearlyInterestRate = 
                        Console.getDouble("Enter yearly interest rate: ");            
                int years = 
                        Console.getInt("Enter number of years:      ");
                
                // call the future value method
                double futureValue = Financial.calculateFutureValue(
                        monthlyInvestment, yearlyInterestRate, years);
    
                // format and displayLine the result
                Console.displayLine("Future value:               " + 
                        NumberFormat.getCurrencyInstance().format(futureValue));
                Console.displayLine();
    
                // see if the user wants to continue
                choice = Console.getString("Continue? (y/n): ");
                Console.displayLine();
            }
            Console.displayLine("Bye!");
        }
    }
    Quote Originally Posted by Norm View Post
    Can you explain what the method is supposed to do with the String arg that is passed to it: prompt
    Yeah, I know
    The goal of this exercise is to allow the user to input a monthly investment value with a $ sign, and a yearly interest rate with a % sign. But I suspect that the only way to get the program to cooperate with that is to is to pass in the user's input as a string, because a normal double data type doesn't have such symbols. Of course, as you saw in my code of post#1, my attempt to convert a double to a string using the toString method didn't work. However, we are also dealing with type Console here, as the error message on line 7 says in my code at the bottom of this post. In fact, if you observe the syntax in Main.java, you will notice that this whole application is of type Console. So maybe prompt is a keyword for type Console?

    Quote Originally Posted by Norm View Post
    Why is there a while(true) loop in the method?
    I'm guessing so that the try catch doesn't allow the program to move on until the user has inputted a valid double.

    All of that being said, here is my latest attempt at getting this getDouble method to work:
    Java Code:
    public static double getDouble(String prompt) {
            double d = 0;
            while (true) {
                System.out.print(prompt);
                try {
                    d = Double.parseDouble(sc.nextLine());
                    if((indexOf('$') == 0) || (indexOf('%') == 0)){//error: The method indexOf(char) is undefined for the type Console
                    	bool = true;//user's inputted entry is still valid?
                    }
                    break;
                } catch (NumberFormatException e) {
                    System.out.println("Error! Invalid decimal. Try again.");
                }
            }
            return d;
        }
    Any other ideas on how to make user inputs such as $44.50 and %4 valid inputs?

  4. #4
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    20,003
    Rep Power
    33

    Default Re: Cannot invoke length() on the primitive type double

    here is my latest attempt
    You missed this question I asked:
    Can you explain what the method is supposed to do with the String argument named prompt that is passed to it?

    I'll ask questions one at a time to be sure you respond to them.

    Note: I just saw this:
    maybe prompt is a keyword for type Console?
    How can that be possible? The variable: prompt is defined as a String.

    As I said before:

    I suggest that you start over. Describe what the method does. Write down what args it takes and what it returns.
    Write down the steps the method should take and work on them one at a time. Write the steps to take as comments in the code and then write the code for one step, compile and execute it. Fixing any errors before moving to the next step.
    Last edited by Norm; 07-12-2016 at 03:33 AM.
    If you don't understand my response, don't ignore it, ask a question.

  5. #5
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    13,541
    Rep Power
    27

    Default Re: Cannot invoke length() on the primitive type double

    Quote Originally Posted by Sam_JavaTheHut5580 View Post
    But I suspect that the only way to get the program to cooperate with that is to is to pass in the user's input as a string, because a normal double data type doesn't have such symbols.
    Do you suspect, or do you know?
    In other words, do you get an error using the original code when you enter $23.99?
    If so, what error do you get?
    Please do not ask for code as refusal often offends.

    ** This space for rent **

  6. #6
    Join Date
    Mar 2016
    Posts
    93
    Rep Power
    0

    Default Re: Cannot invoke length() on the primitive type double

    Quote Originally Posted by Norm View Post
    You missed this question I asked:
    Can you explain what the method is supposed to do with the String argument named prompt that is passed to it?
    Java Code:
    public static double getDouble(String prompt) {
            double d = 0;
            while (true) {//while catch block is still catching an error?
                System.out.print(prompt);//print out hard-coded string argument from Main.java
                try {
                    d = Double.parseDouble(sc.nextLine());//convert double to string
                    break;//I have no clue what this is doing here. Do you?
                } catch (NumberFormatException e) {
                    System.out.println("Error! Invalid decimal. Try again.");//detect anything other 
                    //than numbers, or a pair of numbers with only one dot between them
                }
            }
            return d;//try block successful, return the double value entered by user, let program move on
        }
    When I commented out line 4, none of these prompts from Main.java appear in the console when I run the code as it is:
    Cannot invoke length() on the primitive type double-whatthehellisprompt.jpg
    So apparently, these hard-coded prompts in Main.java:
    Cannot invoke length() on the primitive type double-hard-coded-prompts.jpg
    are the string arguments passed into the getDouble method as "prompt".

    I could try to make my own method, but I think "while(true)" is more efficient than:
    Java Code:
    public static double myVersionOfGetDouble(double userInput){
        	 userInput = 0;
        	 while(user input is not a proper double)
         }
    Whichever method version you think I should go with, I still have no idea of what the syntax for:

    "Hey, if the first character entered by the user for monthlyInvestment is a $, and if the first character entered by the user for yearlyInterestRate is a %, then that's okay."

    other than:
    Java Code:
    if((indexOf('$') == 0) || (indexOf('%') == 0)){
                        bool = false//exit the while loop, because the $ and % signs do not invalidate the double value entered by user
                    }

  7. #7
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    13,541
    Rep Power
    27

    Default Re: Cannot invoke length() on the primitive type double

    Why not just change the prompt to:
    Enter monthly investment: $
    ?
    Please do not ask for code as refusal often offends.

    ** This space for rent **

  8. #8
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    20,003
    Rep Power
    33

    Default Re: Cannot invoke length() on the primitive type double

    Java Code:
                    d = Double.parseDouble(sc.nextLine());//convert double to string
    The comment on that line does not describe what that line does.
    Assuming that sc is a Scanner object, the line does two things:
    1) sc.nextLine() reads a line into a String using the Scanner class's nextLine method
    2) converts the String that was read into a double value in the d variable
    If you don't understand my response, don't ignore it, ask a question.

  9. #9
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    6,226
    Rep Power
    14

    Default Re: Cannot invoke length() on the primitive type double

    This seems to be an academic exercise. In reality, I would just write a getAmount and getPercentage method with appropriate prompts. I would employ
    the getDouble method or variation thereof within each of those to validate the input. For the academic solution, I would investigate regular expressions.

    Regards,
    Jim
    Last edited by jim829; 07-12-2016 at 04:54 PM.
    The JavaTM Tutorials | SSCCE | Java Naming Conventions
    Poor planning on your part does not constitute an emergency on my part

Similar Threads

  1. Having trouble with primitive type 'long'
    By Sizzlewump in forum New To Java
    Replies: 7
    Last Post: 04-11-2016, 07:18 AM
  2. Passing Primitive Data Type Arguments
    By tariqm in forum New To Java
    Replies: 6
    Last Post: 04-15-2012, 12:58 PM
  3. Replies: 5
    Last Post: 04-02-2012, 02:26 PM
  4. Primitive data type and class
    By Roselicious in forum New To Java
    Replies: 3
    Last Post: 04-19-2010, 03:27 PM
  5. JNI accessing non primitive data type
    By H_P in forum Advanced Java
    Replies: 1
    Last Post: 04-14-2010, 05:43 AM

Posting Permissions

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