Results 1 to 15 of 15
  1. #1
    brycepower1 is offline Member
    Join Date
    May 2011
    Posts
    39
    Rep Power
    0

    Cool adding numbers in a string?

    im trying to add something to this program where i can write like say 2+2 in a box and the answer 4will apear in another box

    so i would have something like

    System.out.println(kbReader.nextLine());

    but how would i make this work?

    unless im mistaken if it's in string format it will be considered a quote and will not add, and if it's an int the add sign will make it crash. any ideas?

  2. #2
    Junky's Avatar
    Junky is offline Grand Poobah
    Join Date
    Jan 2011
    Location
    Dystopia
    Posts
    3,789
    Rep Power
    7

    Default

    If you are doing something simple like 4 * 7 then you need to get the text from the textfield, parse it into the three components (operand1, operator, operand2), use a swith or if statement on the operator, apply it to the 2 operands to get the result, disply the result in second textfield.

    If you want to do something more complex like 2 + 3 * 5 then you will need to convert your expression into postfix form (2 3 5 * +) before you can evaluate it. This is a lot more difficult and will involve using one or more Stack objects.

  3. #3
    pbrockway2 is offline Moderator
    Join Date
    Feb 2009
    Location
    New Zealand
    Posts
    4,565
    Rep Power
    12

    Default

    To treat the string as a numerical expression and evaluate it you would have to parse it: that it you would have to write code that recognises that it is made up of two numbers and an addition. (and so on for all other possible expressions).

    Java allows you to work with expressions as if they were JavaScript (Rhino). See, for example, this article. Another popular scripting language is Beanshell which is very close to Java.

  4. #4
    brycepower1 is offline Member
    Join Date
    May 2011
    Posts
    39
    Rep Power
    0

    Default

    so thier isnt any way to make java think that what you type into there is part of the coding?

  5. #5
    DarrylBurke's Avatar
    DarrylBurke is offline Member
    Join Date
    Sep 2008
    Location
    Madgaon, Goa, India
    Posts
    11,202
    Rep Power
    19

    Default

    Java doesn't think.

    db

  6. #6
    brycepower1 is offline Member
    Join Date
    May 2011
    Posts
    39
    Rep Power
    0

    Default

    darn i thought life would be easy

  7. #7
    DarrylBurke's Avatar
    DarrylBurke is offline Member
    Join Date
    Sep 2008
    Location
    Madgaon, Goa, India
    Posts
    11,202
    Rep Power
    19

    Default

    Scripting for the Java Platform
    Java Code:
    import java.awt.GridLayout;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.script.*;
    import javax.swing.*;
    
    public class ScriptEval {
    
      public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
    
          public void run() {
            new ScriptEval().makeUI();
          }
        });
      }
    
      public void makeUI() {
        final JTextField input = new JTextField(20);
        final JLabel result = new JLabel("");
        JButton button = new JButton("Evaluate");
        button.addActionListener(new ActionListener() {
    
          public void actionPerformed(ActionEvent ae) {
            ScriptEngineManager manager = new ScriptEngineManager();
            ScriptEngine engine = manager.getEngineByName("javascript");
            try {
              Object value = engine.eval(input.getText());
              result.setText(String.valueOf(value));
            } catch (ScriptException se) {
              result.setText("Error");
              se.printStackTrace();
            }
    
          }
        });
    
        JFrame frame = new JFrame();
        frame.setLayout(new GridLayout(3, 1));
        frame.add(input);
        frame.add(button);
        frame.add(result);
        frame.pack();
    
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
      }
    }
    Have fun!

    db

  8. #8
    brycepower1 is offline Member
    Join Date
    May 2011
    Posts
    39
    Rep Power
    0

    Default

    wow thats alot more than i had expected darrylburke, cant say that i was looking to copy and paste it, but this will be a huge help when writing my own version of it, Thank you.

  9. #9
    brycepower1 is offline Member
    Join Date
    May 2011
    Posts
    39
    Rep Power
    0

    Default

    while i work that out anyone want to give me some opinions on my Days Old project? basicly it tells you exactly how old you are in days. it was a project of mine back in school that i blew off and never finnished until tonight

    Java Code:
    import java.io.*;
    import java.util.*;
    public class days
    {
        public static void main (String args[])
        {
            Scanner kbReader = new Scanner (System.in);
            System.out.println("Would you like to have your fortune told? just give me your age and i will tell you!");
            System.out.println("Soooo When when were you born? stating with the month ending with the year (click enter after each one)");
            String birthmonthstring = kbReader.nextLine();
            String birthdaystring = kbReader.nextLine();
            String birthyearstring = kbReader.nextLine();
            System.out.println("Come to think of it i have no idea what day it is...");
            System.out.println("Mind filling me in? same format as befor click enter after each one");
            String monthstring = kbReader.nextLine();
            String daystring = kbReader.nextLine();
            String yearstring = kbReader.nextLine();
            int birthday = Integer.parseInt(birthdaystring);
            int birthmonth = Integer.parseInt(birthmonthstring);
            int birthyear = Integer.parseInt(birthyearstring);
            int day = Integer.parseInt(daystring);
            int month = Integer.parseInt(monthstring);
            int year = Integer.parseInt(yearstring);
            int yeardays = ((year-birthyear) * 365);
            month = month - 1;
            birthmonth = birthmonth - 1;
            int x=0;
            int y=0;
            int ly=0;
            int yearsold = (year-birthyear);
            {
                if(month == 0){x = 0;}
                else if (birthmonth == 1) {x = 31;}
                else if(birthmonth == 2){x = 59;}
                else if(birthmonth == 3){x = 90;}
                else if(birthmonth == 4){x = 120;}
                else if(birthmonth == 5){x = 151;}
                else if(birthmonth == 6){x = 181;}
                else if(birthmonth == 7){x = 212;}
                else if(birthmonth == 8){x = 243;}
                else if(birthmonth == 9){x = 273;}
                else if(birthmonth == 10){x = 304;}
                else if(birthmonth == 11){ x = 334;}
                else{System.out.println("I may be a computer but im not stupid you were not born in that month");}
                if(month == 0){y = 0;}
                else if (month == 1) {y = 31;}
                else if(month == 2){y = 59;}
                else if(month == 3){y = 90;}
                else if(month == 4){y = 120;}
                else if(month == 5){y = 151;}
                else if(month == 6){y = 181;}
                else if(month == 7){y = 212;}
                else if(month == 8){y = 243;}
                else if(month == 9){y = 273;}
                else if(month == 10){y = 304;}
                else if(month == 11){ y = 334;}
                else{System.out.println("You lier thant's not what month it is...");}
            } 
            do{
                if (year < 100){
                    if (year > 40){year = year + 1900;}
                    else{year = year + 2000;}
                }
                if (year % 4 == 0){
                    if (year % 100 != 0){ly++;}
                    else if (year % 400 == 0){ly++;}
                    else{System.out.println("");}
                }
                else {System.out.println("");}
                yearsold--;
                year--;
            }while (yearsold>0);
            int finaldaysold = (((y+day)-(x+birthday))+yeardays+ly);
            System.out.println("You are " + finaldaysold + " days old.");
        }
    }

  10. #10
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    11,953
    Rep Power
    19

    Default

    Java Code:
                if(month == 0){x = 0;}
                else if (birthmonth == 1) {x = 31;}
    I think that first one should be birthmonth, not month?

  11. #11
    JeffGrigg is offline Member
    Join Date
    Aug 2011
    Posts
    95
    Rep Power
    0

    Default

    It's a good effort.

    I don't think that it properly considers leap years in your birth year or the current year.

    You can get the current date (and time) quite easily in Java. You don't have to ask the user.

    I would probably use 'java.util.GregorianCalendar'. Or better yet Joda Time. But doing it yourself can be a good exercise.

  12. #12
    brycepower1 is offline Member
    Join Date
    May 2011
    Posts
    39
    Rep Power
    0

    Default

    nice catch tolls, and you have a point jeff, the leap year formula will tell me if it's a leap year or not but it dows not acount for what month you were born in, in the leap year, like say you were born after febuary on a leap year, it will stay say that you were alive during that leap year day even though you hadnt been born yet.

    i'll probley put an if statment tword the end that will subtract 1 day if you were born yesterday on a leap year.

  13. #13
    brycepower1 is offline Member
    Join Date
    May 2011
    Posts
    39
    Rep Power
    0

    Default

    alright how's this look to you?
    other than all the extra imports that is
    Java Code:
    import java.io.*;
    import java.util.*;
    import java.util.Locale;
    import java.text.DateFormat;
    import java.applet.Applet;
    import java.awt.Color;
    import java.awt.Graphics;
    import java.text.SimpleDateFormat;
    import java.awt.event.*;
    import java.applet.*;
    import java.awt.*;
    import javax.swing.JComponent;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import java.awt.Dimension;
    import java.awt.Graphics2D;
    import java.util.Random;
    import java.lang.Math.*;
    
    public class days
    {
        public static void main (String args[])
        {
            Scanner kbReader = new Scanner (System.in);
            Date dateNow = new Date ();
            SimpleDateFormat dateformatDD = new SimpleDateFormat("dd");
            SimpleDateFormat dateformatMM = new SimpleDateFormat("MM");
            SimpleDateFormat dateformatYYYY = new SimpleDateFormat("yyyy");
            String daystring = new String( dateformatDD.format( dateNow ) );
            String monthstring = new String( dateformatMM.format( dateNow ) );
            String yearstring = new String( dateformatYYYY.format( dateNow ) );
            System.out.println("Would you like to have your fortune told? just give me your age and i will tell you!");
            System.out.println("Soooo When when were you born? stating with the month ending with the year (click enter after each one)");
            String birthmonthstring = kbReader.nextLine();
            String birthdaystring = kbReader.nextLine();
            String birthyearstring = kbReader.nextLine();
            int birthday = Integer.parseInt(birthdaystring);
            int birthmonth = Integer.parseInt(birthmonthstring);
            int birthyear = Integer.parseInt(birthyearstring);
            int day = Integer.parseInt(daystring);
            int month = Integer.parseInt(monthstring);
            int year = Integer.parseInt(yearstring);
            int yeardays = ((year-birthyear) * 365);
            month = month - 1;
            birthmonth = birthmonth - 1;
            int x=0;
            int y=0;
            int ly=0;
            int yearsold = (year-birthyear);
            {
                if(birthmonth == 0){x = 0;}
                else if (birthmonth == 1) {x = 31;}
                else if(birthmonth == 2){x = 59;}
                else if(birthmonth == 3){x = 90;}
                else if(birthmonth == 4){x = 120;}
                else if(birthmonth == 5){x = 151;}
                else if(birthmonth == 6){x = 181;}
                else if(birthmonth == 7){x = 212;}
                else if(birthmonth == 8){x = 243;}
                else if(birthmonth == 9){x = 273;}
                else if(birthmonth == 10){x = 304;}
                else if(birthmonth == 11){ x = 334;}
                else{System.out.println("I may be a computer but im not stupid you were not born in that month");}
                if(month == 0){y = 0;}
                else if (month == 1) {y = 31;}
                else if(month == 2){y = 59;}
                else if(month == 3){y = 90;}
                else if(month == 4){y = 120;}
                else if(month == 5){y = 151;}
                else if(month == 6){y = 181;}
                else if(month == 7){y = 212;}
                else if(month == 8){y = 243;}
                else if(month == 9){y = 273;}
                else if(month == 10){y = 304;}
                else if(month == 11){ y = 334;}
                else{System.out.println("You lier thant's not what month it is...");}
            } 
            do{
                if (year < 100){
                    if (year > 40){year = year + 1900;}
                    else{year = year + 2000;}
                }
                if (year % 4 == 0){
                    if (year % 100 != 0){
                        if ((yearsold == 0)&&(birthmonth>1)){System.out.print("");}
                        else{ly++;}
                    }
                    else if (year % 400 == 0){
                        if ((yearsold == 0)&&(birthmonth>1)){System.out.print("");}
                        else{ly++;}
                    }
                    else{System.out.println("");}
                }
                else {System.out.println("");}
                yearsold--;
                year--;
            }while (yearsold>=0);
            int finaldaysold = (((y+day)-(x+birthday))+yeardays+ly);
            System.out.println("You are " + finaldaysold + " days old.");
        }
    }
    Last edited by brycepower1; 08-19-2011 at 12:03 PM.

  14. #14
    JeffGrigg is offline Member
    Join Date
    Aug 2011
    Posts
    95
    Rep Power
    0

    Default

    I notice that you put in special conditions for "born in January or February of a leap year." But nothing for "today is after February 29th of a leap year."

    I think that this code could be a good starting point for...
    • a JUnit testing exercise -- testing all the boundry and error conditions
    • a refactoring excersise: Eliminate code duplication by creating a "MyDate" class or some reusable function


    Generally, I think this kind of problem is best solved by creating a function that will convert year-month-day to a "number of days since date X" value. Then simple integer subtraction gives you the correct answer.

    Refactoring the given code into a "days since date X" in simple easy steps could be a very interesting and educational experience.

    I like "days since January 1st, 1970", but consider also Wikipedia "Julian day" Entry

  15. #15
    Joel's Avatar
    Joel is offline Member
    Join Date
    May 2011
    Location
    Placerville, CA
    Posts
    86
    Rep Power
    0

    Default

    great program. I remember actually doing something similar. I'm not sure how the other guys on the Forum feel, but personally what works best for me is if you keep the main() method as clean as possible. I usually make programs of this scope and my main() method consists only of class calls. Easier to debug.
    PS I like what @DarrylBurke said: Java doesn't think.
    PSS I think I am starting to realize that finally!
    ~MSP430 Lover~

Similar Threads

  1. adding numbers
    By droidus in forum New To Java
    Replies: 7
    Last Post: 03-09-2011, 04:26 AM
  2. Adding squared numbers in a loop
    By kurap3ka in forum New To Java
    Replies: 5
    Last Post: 02-10-2011, 08:13 AM
  3. adding numbers in an array together
    By pds8475 in forum New To Java
    Replies: 3
    Last Post: 01-22-2011, 07:23 PM
  4. Adding numbers in an array?
    By hawaiifiver in forum New To Java
    Replies: 9
    Last Post: 01-22-2009, 03:50 AM
  5. Adding numbers in array
    By Shaolin in forum New To Java
    Replies: 1
    Last Post: 11-15-2007, 06:30 PM

Tags for this Thread

Posting Permissions

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