Results 1 to 14 of 14
Like Tree1Likes
  • 1 Post By Tolls

Thread: java.lang.IllegalArgumentException: Cannot format given Object as a Number

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

    Default java.lang.IllegalArgumentException: Cannot format given Object as a Number

    Hi, I'm new to the Eclipse IDE. I'm trying to experiment with the NumberFormat package, and there appears to be no errors in the following code:
    Java Code:
    import java.text.NumberFormat;
    import java.util.Scanner;
    public class SmartCurrency {
    	public static void main(String[] args){
    		
    		Scanner sc = new Scanner(System.in);
    		
    		System.out.println("Enter a double for a price.");
    		String price = sc.nextLine();
    		String priceFormatted = NumberFormat.getCurrencyInstance().format(price);
    		System.out.println(priceFormatted);
    	}
    }
    But the console says otherwise:
    java.lang.IllegalArgumentException: Cannot format given Object as a Number-currencyproblem.png
    As you can see, the sample input I used was 678. The question is, why didn't it just simply print out something like "$678.00"?

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

    Default Re: java.lang.IllegalArgumentException: Cannot format given Object as a Number

    Probably because price is a String and not a number. Try the following:

    Java Code:
    double price = sc.nextDouble();
    Regards,
    Jim
    The JavaTM Tutorials | SSCCE | Java Naming Conventions
    Poor planning on your part does not constitute an emergency on my part

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

    Default Re: java.lang.IllegalArgumentException: Cannot format given Object as a Number

    Thanks for the fast response Jim
    Next issue. When I run the following program:
    Java Code:
    import java.util.Scanner;
    import java.text.NumberFormat;
    public class Strings01 {
    	public static void main(String[] args){
    		
    		Scanner sc = new Scanner(System.in);
    		
    		System.out.println("Enter a raw number that you want converted into a price.");
    		double price = sc.nextDouble();
    		String priceFormatted = NumberFormat.getCurrencyInstance().format(price);
    		System.out.println(priceFormatted);
    		
    		System.out.println("Do you like South Park? Enter y if you do, or n if you don't.");
    		String yesOrNo = sc.nextLine();
    		if(yesOrNo.equalsIgnoreCase("y"))
    		{
    			System.out.println("Blame Canada.");
    		}
    		else if(yesOrNo.equalsIgnoreCase("n")){
    			System.out.println("Aye! Respect my authority!");
    		}
    	}
    }
    I'm stuck at where I ask the user to enter a y or n. It won't accept any input:
    java.lang.IllegalArgumentException: Cannot format given Object as a Number-conditionalstring.png
    What's going on?

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

    Default Re: java.lang.IllegalArgumentException: Cannot format given Object as a Number

    You've encountered one of the oddities about Scanner.

    nextXXX() (where XXX is int, double etc, not line) and next() all leave the token in the buffer. In the case of text input as above that token is the newline.

    nextLine() reads up to and including the next token.
    So:
    Java Code:
    int foo = sc.nextInt();
    String bar = sc.nextLine();
    will result in nextInt reading in a number then nextLine reading in the leftover newline, so bar would be empty.

    The easy fix for your issue is to use next() instead of nextLine().
    Please do not ask for code as refusal often offends.

    ** This space for rent **

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

    Default Re: java.lang.IllegalArgumentException: Cannot format given Object as a Number

    This is annoying:
    Java Code:
    import java.util.Scanner;
    import java.text.NumberFormat;
    public class WhileLoop01 {
    	public static void main(String[] args){
    		
    		Scanner sc = new Scanner(System.in);
    		
    		System.out.println("Enter a raw number that you want converted into a price.");
    		double price = sc.nextDouble();
    		String priceFormatted = NumberFormat.getCurrencyInstance().format(price);
    		System.out.println(priceFormatted);
    		
    		String choice;
    		while(!choice.equalsIgnoreCase("y") || !choice.equalsIgnoreCase("n"))
    		{
    			choice = sc.next();//instead of using .nextLine()
    			System.out.println("Do you like South Park? Enter y if you do, or n if you don't.");			
    			if(choice.equalsIgnoreCase("y"))
    			{
    				System.out.println("Blame Canada.");
    			}
    			else if(choice.equalsIgnoreCase("n")){
    				System.out.println("Aye! Respect my authority!");
    			}
    		}		
    	}
    }
    I'm trying to use a while loop to not exit until the user inputs either "y" or "n". Problem is, if I don't declare the String choice variable before the while loop, the while loop doesn't know what choice is. Furthermore, if I initialize the choice variable, I'm hard coding it to that initialization, which defeats the purpose of getting user input. How do I get around this?

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

    Default Re: java.lang.IllegalArgumentException: Cannot format given Object as a Number

    Why not just assign choice the empty string to start?

    Java Code:
    String choice = "";
    A couple other suggestions:

    1. You need to think about your loop expression. Make a truth table
    to ensure you are testing correctly.
    2. Consider using a do/while. Then you won't need to initialize your variable.
    3. Ask the question before you prompt for the answer.

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

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

    Default Re: java.lang.IllegalArgumentException: Cannot format given Object as a Number

    Correct me if I'm wrong, but parsing a string of numbers enables the compiler to view them as actual integers?

    That being said, in the following code:
    Java Code:
    import java.util.Scanner;
    import java.text.NumberFormat;
    public class LineItemApp01 {
    	public static void main(String[] args){
    		
    	System.out.println("Welcome to the Line Item Calculator.");
    	System.out.println();
    	
    	Scanner sc = new Scanner(System.in);
    	String choice = "y";
    	
    		while(choice.equalsIgnoreCase("y"))
    		{
    			System.out.print("Enter Product Code: ");
    			String productCode = sc.nextLine();
    			
    			System.out.print("Enter Quantity:     ");
    			int quantity = Integer.parseInt(sc.nextLine());
    			
    			//Set product price based on product code
    			double price;
    			if(productCode.equalsIgnoreCase("java")){
    				price = 57.50;
    				}
    				else if(productCode.equalsIgnoreCase("jsp")){
    					price = 99.00;
    				}
    				else if(productCode.equalsIgnoreCase("mysql")){
    					price = 67.20;
    				}
    				else{
    					price = 0;
    				}
    				//calculate total
    				double total = price * quantity;
    			}
    		}//end of main method	
    	
    }//end of class
    I don't understand this part:
    java.lang.IllegalArgumentException: Cannot format given Object as a Number-parsingint.png
    quantity is already assigned to the int datatype, so why are we parsing it?

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

    Default Re: java.lang.IllegalArgumentException: Cannot format given Object as a Number

    the 'int quantity' is simply declaring a variable of type int.
    It isn't assigning anything to it.

    The bit to the right is doing the assignment and, without the parseInt call, it would be attempting to assign a String.
    Please do not ask for code as refusal often offends.

    ** This space for rent **

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

    Default Re: java.lang.IllegalArgumentException: Cannot format given Object as a Number

    Hi, I'm trying to use a while loop as input validation to see if the user wants to continue, but due to the error, it doesn't seem to like my logic:
    Java Code:
    /*FutureValue01.java
     * this program prompts user for information needed to get a yearly interest rate,
     * and then converts the yearly total into 12 month segments, in order to display
     * the future value that will result (in accuracy of months)
     */
    import java.util.Scanner;
    import java.text.NumberFormat;
    public class FutureValue01 {
    	public static void main(String[] args){
    		System.out.println("Welcome to the Future Value Calculator.");
    		
    		Scanner sc = new Scanner(System.in);
    		String choice = "y";
    		while(choice.equalsIgnoreCase("y"))
    		{
    			System.out.print("Enter monthly investment:    ");
    			double monthlyInvestment = Double.parseDouble(sc.nextLine());
    			
    			System.out.print("Enter yearly interest rate: ");
    			double yearlyInterestRate = Double.parseDouble(sc.nextLine());
    			
    			System.out.print("Enter number of years:      ");
    			int years = Integer.parseInt(sc.nextLine());
    			
    			//Convert yearly values to monthly values:
    			double monthlyInterestRate = (yearlyInterestRate / 12 / 100);
    			int months = years * 12;
    			
    			//Calculate the future value:
    			double futureValue = 0;
    			int i = 1;
    			while(i < months)
    			{
    				futureValue += monthlyInvestment;
    				double monthlyInterestAmt = (futureValue * monthlyInterestRate);
    				futureValue += monthlyInterestAmt;
    				i++;
    			}
    			//format and display the result:
    			System.out.println("Future value:           " +
    					NumberFormat.getCurrencyInstance().format(futureValue));
    			System.out.println();
    			//see if the user wants to continue:
    			while((choice != y) && (choice != n))//error: y cannot be resolved to a variable
    			{
    				System.out.print("Continue? (y/n): ");
    				choice = sc.nextLine();
    				System.out.println();
    			}			
    			
    		}//end of main while loop
    		sc.close();
    		System.out.println("");
    	}
    }
    In other words, I don't want to allow the program to exit until the user enters either y for yes or n for no, but wthout input validation, the program won't know what to do if the user types in anything other than y or n. How do i fix this?

    By the way, let me know if I should start a new thread, as my questions in this thread have not been entirely related to the title I originally gave this thread when I started it. I'm just trying to avoid needlessly polluting the eclipse subforums with one new thread after another.

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

    Default Re: java.lang.IllegalArgumentException: Cannot format given Object as a Number

    Compare how you check for a "y" in your first while loop with how you are checking for a "y" or "n" in the second.
    In addition, you want to actually read in a value into choice before doing that check, otherwise choice will never be anything other than its start value of "y".
    Please do not ask for code as refusal often offends.

    ** This space for rent **

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

    Default Re: java.lang.IllegalArgumentException: Cannot format given Object as a Number

    In situations like this, it is may be more straight forward to use a do while construct:

    Java Code:
    declare the variable answer
    do {
        // do some stuff
        print "Do you want to continue?"
        get answer
    } while (answer is yes);
    Note that the pseudo-code loop above will terminate upon any value of answer that is not yes.

    Regards,
    Jim
    The JavaTM Tutorials | SSCCE | Java Naming Conventions
    Poor planning on your part does not constitute an emergency on my part

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

    Default Re: java.lang.IllegalArgumentException: Cannot format given Object as a Number

    Quote Originally Posted by jim829 View Post
    In situations like this, it is may be more straight forward to use a do while construct:

    Java Code:
    declare the variable answer
    do {
        // do some stuff
        print "Do you want to continue?"
        get answer
    } while (answer is yes);
    Note that the pseudo-code loop above will terminate upon any value of answer that is not yes.

    Regards,
    Jim
    Yes it will. Any idea on how to make it only terminate if choice = "n"? If the user types in something other than "n" or "y", I want the program to re-ask the user if he wants to continue:
    java.lang.IllegalArgumentException: Cannot format given Object as a Number-jumpback.png
    What's the best way to do that? My current do while loop looks like this:
    Java Code:
    Scanner sc = new Scanner(System.in);
    		String choice = "";
    		//while(choice.equalsIgnoreCase("y"))
    		do
    		{
    			//Blah Blah Blah, do some calculations and print some results...
    			
    			//see if the user wants to continue:
    			System.out.print("Continue? (y/n): ");
    			choice = sc.nextLine();
    			if(choice.equalsIgnoreCase("n"))
    			{
    				System.out.println("Okay see ya!");
    				sc.close();
    			}
    			else if(!choice.equalsIgnoreCase("y") && !choice.equalsIgnoreCase("n"))
    			{
    				//jump back to asking if user wants to continue?
    			}
    			
    		}while(choice.equalsIgnoreCase("y"));

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

    Default Re: java.lang.IllegalArgumentException: Cannot format given Object as a Number

    Simply put the prompt for continuation inside another do while loop, checking for yes or no.

    Regards,
    Jim
    The JavaTM Tutorials | SSCCE | Java Naming Conventions
    Poor planning on your part does not constitute an emergency on my part

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

    Default Re: java.lang.IllegalArgumentException: Cannot format given Object as a Number

    At this point I would have pulled the whole "do you want to continue" stuff into its own method, that returns a boolean:
    Java Code:
    do {
        stuff
    } while (userWantsToContinue());
    That hides all the nastiness away from the basic flow of your code.

    In fact, there's loads of bits you could do that with...
    jim829 likes this.
    Please do not ask for code as refusal often offends.

    ** This space for rent **

Similar Threads

  1. Hibernate java.lang.IllegalArgumentException
    By rwelton in forum Hibernate
    Replies: 0
    Last Post: 02-11-2012, 10:16 PM
  2. java.lang.IllegalArgumentException: im == null!
    By simantoch in forum Java 2D
    Replies: 4
    Last Post: 04-12-2011, 12:00 PM
  3. JPA java.lang.IllegalArgumentException
    By johnwcv in forum Advanced Java
    Replies: 0
    Last Post: 03-17-2011, 10:17 PM
  4. java.lang.IllegalArgumentException error occurs
    By clint in forum New To Java
    Replies: 1
    Last Post: 12-01-2010, 04:37 PM
  5. Replies: 1
    Last Post: 08-07-2009, 09:37 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
  •