Results 1 to 13 of 13
Like Tree1Likes
  • 1 Post By Norm

Thread: switch statement doesn't seem to work as intended

  1. #1
    jaavanewb is offline Member
    Join Date
    Mar 2017
    Posts
    13
    Rep Power
    0

    Default switch statement doesn't seem to work as intended

    I have a calculator program which should act as follows:
    Enter an operator followed by a number:
    *5
    the program should then perform the operation and then print out the last number and the new number. I have coded the program to perform the operation. I could easily do this in main, but I am really struggling to make my code more object oriented. The switch statement I have created will perform addition, and for some reason when I do subtraction it also performs addition. None of the other operators seem to work as intended.

    Outputs
    Java Code:
    Enter an operator and a number:
    +5
    5.0
    
    Enter an operator and a number:
    -5
    5.0
    
    
    Enter an operator and a number:
    +5
    Enter an operator and a number:
    *2
    Exception in thread "main" java.lang.NumberFormatException: For input string: "*2"
    	at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:2043)
    	at sun.misc.FloatingDecimal.parseDouble(FloatingDecimal.java:110)
    	at java.lang.Double.parseDouble(Double.java:538)
    	at Calculator.whatOperator(Calculator.java:40)
    	at Calculator.aResult(Calculator.java:29)
    	at Main.main(Main.java:30)
    
    
    Enter an operator and a number:
    +5
    Enter an operator and a number:
    /5
    Exception in thread "main" java.lang.NumberFormatException: For input string: "/5"
    	at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:2043)
    	at sun.misc.FloatingDecimal.parseDouble(FloatingDecimal.java:110)
    	at java.lang.Double.parseDouble(Double.java:538)
    	at Calculator.whatOperator(Calculator.java:40)
    	at Calculator.aResult(Calculator.java:29)
    	at Main.main(Main.java:30)


    Java Code:
    Calculator Class
    
    import java.util.Scanner;
    public class Calculator {
    	private final int RESET = 0;
    	private double number = 0;
    	private double result = 0; 
    	private char operator;
    	private Scanner keyboard = new Scanner(System.in);
    	public Calculator(double number)
    	{
    		this.number = number;
    		
    	}
    	public void reset()
    	{
    		this.number = RESET;
    	}
            // the whatOperator method is called for the calculator that calls aResult. then the result is returned as the new value
    	public double aResult(Calculator other)
    	{
    		
    		other.whatOperator();
    		this.result = other.result;
    		return result;
    		
    	} 
    	// here the entry should be parsed, the operator isolated, and the operation performed based on entry
    	public void whatOperator()
    	{
    		
    		String operatorString = null;
    		operatorString = enterNumber();
    		double theNumber = Double.parseDouble(operatorString);
    		char theOperator = operatorString.charAt(0);
    		this.operator = theOperator;
    		operatorString =" ";
    		operatorString += theOperator;
    		
    		
    		switch(operatorString){
    		case " *":
    		result = getNumber() * theNumber;
    		break;
    		case " /":
    		result = getNumber() / theNumber;
    		break;
    		case " +":
    		result = getNumber() + theNumber;
    		break;
    		case " -":
    		result = getNumber() - theNumber;
    		break;
    		case " R":
    		result = RESET;
    		break;
    		case " P":
    		System.out.println("Goodbye");
    		System.exit(0);
    		
    	}
    	
    	
    }
    public double add(double secondNumber)
    {
    	result = number + secondNumber;
    	return result;
    	
    }
    public double divide(double secondNumber)
    {
    	result = number / secondNumber;
    	return result;
    }
    public double multiply(double secondNumber)
    {
    	result = number * secondNumber;
    	return result;
    }
    public void subtract(double secondNumber)
    {
    	result = number - secondNumber;
    }
    
    	 
    public double getNumber()
    {
    	return number;
    }
    // the setNumber method will be used in conjunction with the aResult() method to give the calculator a new number
    public void setNumber(double number)
    {
    	this.number = number;
    }
    	public  String enterNumber()
    	{
    		
    		System.out.println("Enter an operator and a number:");
    		String toString = keyboard.nextLine();
    		return toString;
    	}
    	
    }
    Java Code:
    Main class - right now just testing that it works
    public class Main {
    	
    	public static void main (String[] args) {
    		Calculator a = new Calculator(0);
    		a.setNumber(a.aResult(a));
    		a.setNumber(a.aResult(a));
    		String theString = String.valueOf(a.getNumber());
    		System.out.println(theString);
    	}
    }

    once I can get the calculator to function correctly, I will then implement the exception class....

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

    Default Re: switch statement doesn't seem to work as intended

    Exception in thread "main" java.lang.NumberFormatException: For input string: "*2"
    at sun.misc.FloatingDecimal.readJavaFormatString(Floa tingDecimal.java:2043)
    at sun.misc.FloatingDecimal.parseDouble(FloatingDecim al.java:110)
    at java.lang.Double.parseDouble(Double.java:538)
    The code needs to parse the input and not assume the value that was entered was a double.
    *2 and /5 are not valid numeric values.
    -5 and +5 are valid signed numeric values
    If you don't understand my response, don't ignore it, ask a question.

  3. #3
    jaavanewb is offline Member
    Join Date
    Mar 2017
    Posts
    13
    Rep Power
    0

    Default Re: switch statement doesn't seem to work as intended

    so if I change:
    double theNumber = Double.parseDouble(operatorString);
    to:
    double theNumber = Double.valueOf(Double.parseDouble(operatorString)) ;
    it should work?

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

    Default Re: switch statement doesn't seem to work as intended

    it should work?
    It seems sort of silly to ask a question like that (besides the extra turnaround time) when you can enter it in a program, compile and execute it to see if it works.

    Please try it and tell us what happens.
    If you don't understand my response, don't ignore it, ask a question.

  5. #5
    jaavanewb is offline Member
    Join Date
    Mar 2017
    Posts
    13
    Rep Power
    0

    Default Re: switch statement doesn't seem to work as intended

    I get the same result haha. I guess I should write a method which parses the double and then include this within my whatOperator method...but I'm unsure how to do that. How can I write code which will determine what primitive to parse?

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

    Default Re: switch statement doesn't seem to work as intended

    If the user enters the String: *2, the code needs to separate the * from the 2 and process them separately.
    There are many ways to do that. I suspect regular expressions will do it, but I'm not a regexp expert.
    Other ways would be to use a String method to get and test the first character of the String.
    An old class: StringTokenizer also will help with separating tokens.
    jaavanewb likes this.
    If you don't understand my response, don't ignore it, ask a question.

  7. #7
    jaavanewb is offline Member
    Join Date
    Mar 2017
    Posts
    13
    Rep Power
    0

    Default Re: switch statement doesn't seem to work as intended

    I am thinking the tokenizer is the way to go. thanks for your help

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

    Default Re: switch statement doesn't seem to work as intended

    If the assumption is there is a single character operator, followed directly by the number, then use charAt and substring.

    The charAt(0) will give you the operator symbol that you can then do a switch statement on, and the substring() call will give you the rest, that you can then use Double.parse on (as you have tried).

    ETA: Note that StringTokenizer is an old class that shouldn't be used anymore. The recommendation is to use the split() method on String instead. However, I don't think this problem requires anything like that, unless there is a convenient space to split on.
    Last edited by Tolls; 03-07-2017 at 09:26 AM.
    Please do not ask for code as refusal often offends.

    ** This space for rent **

  9. #9
    jaavanewb is offline Member
    Join Date
    Mar 2017
    Posts
    13
    Rep Power
    0

    Default Re: switch statement doesn't seem to work as intended

    yeah I actually figured it out...it was an easy fix just needed to add .substring(1) to the double theNumber

  10. #10
    jaavanewb is offline Member
    Join Date
    Mar 2017
    Posts
    13
    Rep Power
    0

    Default Re: switch statement doesn't seem to work as intended

    Is there a way to code so that the R and P operators in the above code will function correctly? I would like to essentially skip the double declaration if operatorString.substring(1) has no value.... I have tried using if statements like
    Java Code:
    if(operatorString.substring(1) == "")
    theNumber = 0;
    and
    Java Code:
    if(operatorString.substring(1) == null)
    theNumber = 0;

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

    Default Re: switch statement doesn't seem to work as intended

    Use the equals() method when comparing strings, not the == operator
    Also the String class has a method to test if a String is empty

    Note: The String returned by the substring method won't be null.
    If you don't understand my response, don't ignore it, ask a question.

  12. #12
    jaavanewb is offline Member
    Join Date
    Mar 2017
    Posts
    13
    Rep Power
    0

    Default Re: switch statement doesn't seem to work as intended

    great! so I just needed to do substring(1).equals("")
    another question....if I want to write an if statement such that every boolean within is tested to be false, would I write
    if(!boolean || boolean) or would I have to write if(!boolean || !boolean)?

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

    Default Re: switch statement doesn't seem to work as intended

    The String class also has a length method that would tell you how many characters in a String.

    Try writing all the combinations you can think of to see what happens.
    You can print the result directly to see if the expression true or false:
    Java Code:
      System.out.println(!boolean || boolean);
    If you don't understand my response, don't ignore it, ask a question.

Similar Threads

  1. switch case doesn't work
    By M0TRIX in forum JavaFX
    Replies: 13
    Last Post: 01-26-2015, 02:27 PM
  2. Replies: 3
    Last Post: 11-19-2012, 08:12 PM
  3. keyPressed method doesn't work as intended
    By JohnPringle83 in forum New To Java
    Replies: 6
    Last Post: 05-31-2011, 09:22 PM
  4. Repaint calling Statement Doesn't Work in my code ?
    By nitin_daviet88 in forum CLDC and MIDP
    Replies: 2
    Last Post: 07-24-2010, 03:09 PM
  5. SQL statement doesn't work....
    By pbaudru in forum New To Java
    Replies: 4
    Last Post: 04-08-2010, 09:51 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
  •