Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 9 of 9

Thread: Error of data types and type casting in java program

  1. #1
    Java kindergarten chronoz13's Avatar
    Join Date
    Mar 2009
    Location
    Philippines
    Posts
    659
    Thanks
    177
    Thanked 30 Times in 28 Posts

    Default Error of data types and type casting in java program

    whats wrong with this one ?

    -Program use to convert a weight

    this is the class.
    public class WeightConverterVer2_UNFINISHED
     
    {
     
        private static double planetWeight;
        private static double convertedWeight;
     
        public WeightConverterVer2_UNFINISHED(double givenPlanetWeight)
        {
            planetWeight = givenPlanetWeight;
        }
     
        public double convert(double earthWeight)
        {
            convertedWeight = planetWeight * earthWeight;
            return convertedWeight;
        }
     
    }


    and this is the main program that uses this class

    import java.text.*;
     
    public class WeightConverterVer2Sample_UNFINISHED
     
    {
     
        private static DecimalFormat df = new DecimalFormat("0.00");
     
        public static void main(String[] args)
     
        {
            WeightConverterVer2_UNFINISHED moonWeight = new WeightConverterVer2_UNFINISHED(0.167);
            WeightConverterVer2_UNFINISHED mercuryWeight = new WeightConverterVer2_UNFINISHED(0.4);
            WeightConverterVer2_UNFINISHED venusWeight = new WeightConverterVer2_UNFINISHED(0.9);
            WeightConverterVer2_UNFINISHED jupiterWeight = new WeightConverterVer2_UNFINISHED(2.5);
            WeightConverterVer2_UNFINISHED saturnWeight = new WeightConverterVer2_UNFINISHED(1.1);
     
            double convertedMoonWeight,
                   convertedMercuryWeight,
                   convertedVenusWeight,
                   convertedJupiterWeight,
                   convertedSaturnWeight;
     
            convertedMoonWeight = moonWeight.convert(167);
            convertedMercuryWeight = mercuryWeight.convert(167);
            convertedVenusWeight = venusWeight.convert(167);
            convertedJupiterWeight = jupiterWeight.convert(167);
            convertedSaturnWeight = saturnWeight.convert(167);
     
            System.out.println("Moon Weight Is: " + df.format(convertedMoonWeight));
            System.out.println("Mercury Weight Is: " + df.format(convertedMercuryWeight));
            System.out.println("Venus Weight Is: " + df.format(convertedVenusWeight));
            System.out.println("Jupiter Weight Is: " + df.format(convertedJupiterWeight));
            System.out.println("Saturn Weight Is: " + df.format(convertedSaturnWeight));
        }
     
    }

    whats wrong with my first codes?
    i cant determine the logic behind these

    need help again please.....
    -------









    ive already solved this one with this code and main program..

    THE FOLLOWING CODES ARE THE CORRECT MODIFICATION OF THE PREVIEWS CLASSES

    public class WeightConverter 
     
    {
     
        private double convertedWeight;
        private double planetWeight;
        public WeightConverter(double planetWeightsARGS)
        {
            planetWeight = planetWeightsARGS;
        }
     
       public double convertInMoonWeight(double earthWeight)
        {
            convertedWeight = earthWeight *  planetWeight;
     
            return convertedWeight;
        }
     
        public double convertInMercuryWeight(double earthWeight)
        {
            convertedWeight = earthWeight * planetWeight;
     
            return convertedWeight;
        }
     
        public double convertInVenusWeight(double earthWeight)
        {
            convertedWeight = earthWeight * planetWeight;
     
            return convertedWeight;
        }
     
        public double convertInJupiterWeight(double earthWeight)
        {
            convertedWeight = earthWeight * planetWeight;
     
            return convertedWeight;
        }
     
        public double convertInSaturnWeight(double earthWeight)
        {
            convertedWeight = earthWeight * planetWeight;
     
            return convertedWeight;
        }
     
    }

    MAIN:

    public class WeightConverterSample 
     
    {
        private static DecimalFormat df = new DecimalFormat("0.00");
        public static void main(String[] args)
        {
            WeightConverter moonWeight = new WeightConverter(0.167);
            WeightConverter mercuryWeight = new WeightConverter(0.4);
            WeightConverter venusWeight = new WeightConverter(0.9);
            WeightConverter jupiterWeight = new WeightConverter(2.5);
            WeightConverter saturnWeight = new WeightConverter(1.1);
     
            double yourMoonWeight,
                   yourMercuryWeight,
                   yourVenusWeight,
                   yourJupiterWeight,
                   yourSaturnWeight;
     
            yourMoonWeight = moonWeight.convertInMoonWeight(167);
            yourMercuryWeight = mercuryWeight.convertInMercuryWeight(167);
            yourVenusWeight =  venusWeight.convertInVenusWeight(167);
            yourJupiterWeight = jupiterWeight.convertInJupiterWeight(167);
            yourSaturnWeight = saturnWeight.convertInSaturnWeight(167);
     
            System.out.println("Moon Weight: " + df.format(yourMoonWeight));
            System.out.println("Mercury Weight: " + df.format(yourMercuryWeight));
            System.out.println("Venus Weight: " + df.format(yourVenusWeight));
            System.out.println("Jupiter Weight: " + df.format(yourJupiterWeight));
            System.out.println("Saturn Weight: " + df.format(yourSaturnWeight));
     
     
        }
     
    }

    i just want to understand the error of the first two classes


  2. #2
    Super Moderator Json's Avatar
    Join Date
    Jul 2009
    Location
    Warrington, United Kingdom
    Posts
    1,274
    My Mood
    Happy
    Thanks
    70
    Thanked 156 Times in 152 Posts

    Default Re: Simple Program Error

    Hello, I take it you are seeing the same output for each sysout in your first code there. This is because the variables planetWeight and convertedWeight in the WeightConverterVer2_UNFINISHED class are static.

    This should be alright.

    public class WeightConverterVer2_UNFINISHED {
        private double planetWeight;
     
        private double convertedWeight;
     
        public WeightConverterVer2_UNFINISHED(double givenPlanetWeight) {
            planetWeight = givenPlanetWeight;
        }
     
        public double convert(double earthWeight) {
            convertedWeight = planetWeight * earthWeight;
            return convertedWeight;
        }
    }

    However it might be nicer to just have a utility class with a static method like this.

        public class WeightConverter {
            public static double convertPlanetWeight(double planetWeightFactor, double earthWeight) {
                return planetWeightFactor * earthWeight;
            }
        }
     
        public static void main(String args[]) throws IOException {
            final double convertedMoonWeight = WeightConverter.convertPlanetWeight(0.167, 167);
            final double convertedMercuryWeight = WeightConverter.convertPlanetWeight(0.4, 167);
            final double convertedVenusWeight = WeightConverter.convertPlanetWeight(0.9, 167);
            final double convertedJupiterWeight = WeightConverter.convertPlanetWeight(2.5, 167);
            final double convertedSaturnWeight = WeightConverter.convertPlanetWeight(1.1, 167);
     
            System.out.println("Moon Weight Is: " + df.format(convertedMoonWeight));
            System.out.println("Mercury Weight Is: " + df.format(convertedMercuryWeight));
            System.out.println("Venus Weight Is: " + df.format(convertedVenusWeight));
            System.out.println("Jupiter Weight Is: " + df.format(convertedJupiterWeight));
            System.out.println("Saturn Weight Is: " + df.format(convertedSaturnWeight));
     
        }

    Happy coding!

    // Json

  3. The Following User Says Thank You to Json For This Useful Post:

    chronoz13 (September 1st, 2009)

  4. #3
    Java kindergarten chronoz13's Avatar
    Join Date
    Mar 2009
    Location
    Philippines
    Posts
    659
    Thanks
    177
    Thanked 30 Times in 28 Posts

    Default Re: Simple Program Error

    ahh its because the data members became CLASS data members when i declare them STATIC and anything or any value that i will assign into
    those variables using the CONSTRUCTOR will be CLASS DATA VALUE..

    and any method that will be called inside that class will return the value which is a class data value..


    so it means that there are certain cases that I SHOULD NOT declare a data member as static?
    am I right with this?

  5. #4
    Java kindergarten chronoz13's Avatar
    Join Date
    Mar 2009
    Location
    Philippines
    Posts
    659
    Thanks
    177
    Thanked 30 Times in 28 Posts

    Default Re: Simple Program Error

    and one more thing sir.. i've studied about this a while ago .. and i notice that the construtor has the
    superior capabiliites among the other methods(predefined methods) to control the values for any data members..

    I modified this program several times.. one modification is ..
    i didnt erase the static declarations for the data members, instead i created another data members which is NOT static and using the constructor I assigned the value from a class data members into an instance data member(which is a data member that is not static) and i made it ryt..


    public Constructor(<parameters>)
    {
        classDataMember = <parameters>
        instanceDataMember = classDataMember
    }
     
    public double returnTheValue( )
    {
        return instanceDataMember;
    }

    i've notice the problem and i did someting like this..


    another thing.,
    ive notice that the last instantation of the object for the class and the value(argument) that was passed to the constructor's parameters
    was shared by all the methods.(next statements after the instantation). ----
    WeightConverterVer2_UNFINISHED saturnWeight = new WeightConverterVer2_UNFINISHED(1.1);
    Last edited by chronoz13; September 1st, 2009 at 06:41 AM.

  6. #5
    Super Moderator Json's Avatar
    Join Date
    Jul 2009
    Location
    Warrington, United Kingdom
    Posts
    1,274
    My Mood
    Happy
    Thanks
    70
    Thanked 156 Times in 152 Posts

    Default Re: Simple Program Error

    Yes you are correct, static means its a class member rather than an instance member.

    You should beware that setting static variables from non static methods is not encouraged.

    // Json

  7. The Following User Says Thank You to Json For This Useful Post:

    chronoz13 (September 1st, 2009)

  8. #6
    Super Moderator helloworld922's Avatar
    Join Date
    Jun 2009
    Posts
    2,896
    Thanks
    23
    Thanked 619 Times in 561 Posts
    Blog Entries
    18

    Default Re: Simple Program Error

    You can create a "constructor" of sorts for the static instance of your class.

    just use the keyword static followed by a block.

    Ex: say you wanted a static arrayList that contained a list of allowed operators, but you wanted the list to be final.

    public class Operators
    {
         private static final ArrayList<String> allowedOperators;
     
         static
         {
              allowedOperators = new ArrayList<String>();
              allowedOperators.add("+");
              allowedOperators.add("-");
              allowedOperators.add("*");
              allowedOperators.add("/");
         }
     
         public static ArrayList<String> getAllowedOperators()
         {
              return allowedOperators;
         }
    }

    You can also have multiple static blocks within the same class, but they'll all be executed when the static instance is created.

  9. The Following User Says Thank You to helloworld922 For This Useful Post:

    chronoz13 (September 1st, 2009)

  10. #7
    Java kindergarten chronoz13's Avatar
    Join Date
    Mar 2009
    Location
    Philippines
    Posts
    659
    Thanks
    177
    Thanked 30 Times in 28 Posts

    Default Re: Simple Program Error

    ahh so sir json .. its another programming habit that i have to practice especially here in java community

    tnx for that sir!! atleast now im aware of that.


    Non-static method that has static data member is fine it will compilte without problems.. but its not a good way of making a class.. but ofcoure non-static data members cannot be referenced or cannot be used by static methods..


    am i right with this sir??

    tnx tnx!!

  11. #8
    Super Moderator Json's Avatar
    Join Date
    Jul 2009
    Location
    Warrington, United Kingdom
    Posts
    1,274
    My Mood
    Happy
    Thanks
    70
    Thanked 156 Times in 152 Posts

    Default Re: Simple Program Error

    Yes, try to not use statics if you dont really need them. Once a static is created it will be created forever, hence taking up memory.

    Good use of statics are constants of various things and also good when creating singleton classes. Its also nice for utility classes.

    If you create a utility class with only static methods in it, be sure to create the constructor like this.

    public class MyUtilityClass {
     
        protected MyUtilityClass() {
            throw new UnsupportedOperationException();
        }
     
        public static void myUtilityMethod() {
            // Do some clever utility stuff here
        }
    }

    // Json

  12. The Following User Says Thank You to Json For This Useful Post:

    chronoz13 (September 2nd, 2009)

  13. #9
    Java kindergarten chronoz13's Avatar
    Join Date
    Mar 2009
    Location
    Philippines
    Posts
    659
    Thanks
    177
    Thanked 30 Times in 28 Posts

    Default Re: Simple Program Error

    oh sir.. im not yet on that part.. and im not yet familiar with the modifier 'protected' even with 'utility classes'

    anyway ill keep that code, someday it will be usefull .



    Sir when i declare 'static' in a variable or data member which is not constant ,is it not advisable? nor encouraged?

    i mean static is only use for constants? for it will be a class variable or object? or for 'final' variables?


    here's a sample program exercies that i've made recently ... is this not advisable?

    all the data members are static...

    import javax.swing.*;
    public class VideoStoreMembership
     
    {
     
            private static String memberName;
            private static String memberMiddleName;
            private static String memberLastName;
            private static String memberGender;
            private static String memberAddress;
            private static String memberContactNumber;
            private static String initial;
            private static String initialCapital;
            private static String lowerCase;
            private static String upperCase;
            private static String substrings;
            private static int memberAge;
     
     
            public VideoStoreMembership( )
            {
                memberName = "";
                memberMiddleName = "";
                memberLastName = "";
                memberGender = " ";
                memberAddress = "";
                memberContactNumber = "";
                initial = "";
                initialCapital = "";
                lowerCase = "";
                upperCase = "";
                substrings = "";
                memberAge = 0;
            }
     
            public static String setMemberFirstName( )
            {
                memberName = JOptionPane.showInputDialog(null,"Enter Member's Name:", "NAME", JOptionPane.INFORMATION_MESSAGE);
                initial = memberName.substring(0,1);
                initialCapital = initial.toUpperCase( );
                substrings = memberName.substring(1); 
                upperCase = substrings.toUpperCase( );
                lowerCase = substrings.toLowerCase( );
     
                if(substrings == upperCase || substrings == lowerCase)
                {
                    substrings = substrings.toLowerCase( );
     
                }
     
                else if(substrings != upperCase || substrings != lowerCase)
                {
                    substrings = substrings.toLowerCase( );
                }
     
                return initialCapital + substrings;
            }
     
            public static String setMemberMiddleName( )
            {
                memberMiddleName = JOptionPane.showInputDialog(null, "Enter Member's Middle Name: ", "MIDDLE NAME", JOptionPane.INFORMATION_MESSAGE);
                initial  = memberMiddleName.substring(0,1);
                initialCapital = initial.toUpperCase( );
                substrings = memberMiddleName.substring(1);
                upperCase = substrings.toUpperCase( );
                lowerCase = substrings.toLowerCase( );
     
                if(substrings == upperCase || substrings == lowerCase)
                {
                    substrings = substrings.toLowerCase( );
                }
     
                else if(substrings != upperCase || substrings != lowerCase)
                {
                    substrings = substrings.toLowerCase( );
                }
     
                return initialCapital;
            }
     
            public static String setMemberLastName( )
            {
                memberLastName = JOptionPane.showInputDialog(null, "Enter Member's Last Name", "LAST NAME", JOptionPane.INFORMATION_MESSAGE);
                initial = memberLastName.substring(0,1);
                initialCapital = initial.toUpperCase( );
                substrings = memberLastName.substring(1);
                upperCase = substrings.toUpperCase( );
                lowerCase = substrings.toLowerCase( );
     
                if(substrings == upperCase || substrings == lowerCase)
                {
                    substrings = substrings.toLowerCase( );
                }
     
                else if(substrings != upperCase || substrings != lowerCase)
                {
                    substrings = substrings.toLowerCase( );
                }
     
                return initialCapital + substrings;
            }
     
            public static String setMemberGender( )
            {
                memberGender = JOptionPane.showInputDialog(null, "Enter Member's Gender", "GENDER", JOptionPane.WARNING_MESSAGE);
                initial = memberGender.substring(0,1);
                initialCapital = initial.toUpperCase( );
                substrings = memberGender.substring(1);
                upperCase = substrings.toUpperCase( );
                lowerCase = substrings.toLowerCase( );
     
                if(substrings == upperCase || substrings == lowerCase)
                {
                    substrings = substrings.toLowerCase( );
                }
     
                else if(substrings != upperCase || substrings != lowerCase)
                {
                    substrings = substrings.toLowerCase( );
                }
     
                return initialCapital + substrings;
            }
     
            public static String setMemberAddess( )
            {
                memberAddress = JOptionPane.showInputDialog(null, "Enter Member's Address", "ADDRESS", JOptionPane.INFORMATION_MESSAGE);
     
                return memberAddress;
            }
     
            public static String setMemberContactNumber( )
            {
                memberContactNumber = JOptionPane.showInputDialog(null, "Enter Member's Contact Number", "CONTACT NUMBER", JOptionPane.INFORMATION_MESSAGE);
     
                return memberContactNumber;
            }
     
            public static int setMemberAge( )
            {
                memberAge = Integer.parseInt(JOptionPane.showInputDialog(null,"Enter Member's Age", "AGE", JOptionPane.WARNING_MESSAGE));
     
                if(memberAge <= 12)
                {
                    JOptionPane.showMessageDialog(null, "Only 13-yrs Old Above Can Register For A Membership", "CANNOT PROCEED", JOptionPane.WARNING_MESSAGE);
                    System.exit(0);
                }
     
                else if(memberAge <= 17)
                {
                    JOptionPane.showMessageDialog(null, "You Have Restriction On Renting Video Movies", "UNDER AGE", JOptionPane.WARNING_MESSAGE);
                }
     
                else if(memberAge <= 50)
                {
                    JOptionPane.showMessageDialog(null, "Proceed", "VALID", JOptionPane.INFORMATION_MESSAGE);
                }
     
                else if(memberAge > 50)
                {
                    JOptionPane.showMessageDialog(null, "Validated For Discount", "SENIOR", JOptionPane.WARNING_MESSAGE);
                }
     
                return memberAge;
            }
     
    }
    Last edited by chronoz13; September 2nd, 2009 at 10:44 AM.

Similar Threads

  1. PLEASE HELP!!!! simple java program...
    By parvez07 in forum Object Oriented Programming
    Replies: 5
    Last Post: August 26th, 2009, 06:38 AM
  2. help with simple java program
    By parvez07 in forum Java Theory & Questions
    Replies: 4
    Last Post: August 25th, 2009, 07:19 AM
  3. Simple java program to calculate wall covering of a room
    By parvez07 in forum What's Wrong With My Code?
    Replies: 3
    Last Post: August 22nd, 2009, 03:31 PM
  4. Someone please help me write a simple program!!!
    By ocean123 in forum Loops & Control Statements
    Replies: 3
    Last Post: June 14th, 2009, 09:46 PM
  5. Java program to write game
    By GrosslyMisinformed in forum Paid Java Projects
    Replies: 3
    Last Post: January 27th, 2009, 02:33 PM