Author Topic: Any java programmers? Simple question i have...  (Read 7677 times)

0 Members and 1 Guest are viewing this topic.

Offline tjanuranus

  • Posts: 2234
  • Gender: Male
Any java programmers? Simple question i have...
« on: March 07, 2011, 12:47:48 PM »
This is my first semester ever in college and my first programming course so i don't know a lot...

I'm working on a programming challenge and i came across something i don't know how to do. The second user input is a percent. So they are supposed to enter "50" for 50 percent instead of entered the decimal format. It works great if you just enter 50. But if you type in 50% the program crashes. Is there any way to make it so if the percent sign is entered it doesn't crash? Like maybe a way to ignore it? Thanks. Here is the code.

import javax.swing.JOptionPane;
import java.text.DecimalFormat;

public class Population
{
   public static void main(String[] args)
   {
      String input;      //For getting String input
      int organisms;      //Entered number of organisms.
      double percent;      //User entered percent number
      double percentage;   //Average daily population increase percentage
      int days;         //Number of days population will multiply
      int i;            //For counting loop
      double size = 0;   //Size of population each day.
      double totalSize;
      
      DecimalFormat fmt = new DecimalFormat("0.0");
      
      //Display purpose of program
      JOptionPane.showMessageDialog(null, "This program calculates the daily size of a growing " +
                              "population of organisms.");
      
      //Get starting number of organisms
      input = JOptionPane.showInputDialog("What is the starting number of orgamisms?");
      organisms = Integer.parseInt(input);
      
      //Set input validation
      while (organisms < 2)
      {
         input = JOptionPane.showInputDialog("Number of organisms must be at least 2." +
                                    "\nEnter number of organisms.");
         organisms = Integer.parseInt(input);
      }
      
      //Get the average daily percentage
      input = JOptionPane.showInputDialog("Enter the percentage of average daily population increase.");
      percent = Double.parseDouble(input);
      
      //Get the number of days to multiply by
      input = JOptionPane.showInputDialog("Enter the number of days they will multiply");
      days = Integer.parseInt(input);
      
      //Set another input validation
      while (organisms < 2)
      {
         input = JOptionPane.showInputDialog("Number of days must be at least 1." +
                              "\nEnter number of organisms.");
         days = Integer.parseInt(input);
      }
      
      
      percentage = percent / 100;      //Calculate percentage
      totalSize = organisms;         //Set accumulator number for day 1
      
      for (i=1; i <= days; i++)
      {
         size = (organisms * percentage);

         JOptionPane.showMessageDialog(null, "The size of the population for day " + i +
                             " is " + fmt.format(totalSize) + " orgamisms.");
         totalSize = size + totalSize;
      }
      System.exit(0);
   }
}

Offline mizzl

  • DTF.org Member
  • *
  • Posts: 1769
  • Gender: Male
  • I have officialy been ravenhearted. Thanks Zydar!
Re: Any java programmers? Simple question i have...
« Reply #1 on: March 07, 2011, 12:52:43 PM »
I suggest an if-statement checking the string for a regular expression. If it finds a %, chop it off and resume course. Then just divide by 100

Offline AcidLameLTE

  • Nae deal pal
  • DTF.org Alumni
  • ****
  • Posts: 11134
  • Gender: Male
Re: Any java programmers? Simple question i have...
« Reply #2 on: March 07, 2011, 12:53:03 PM »
Why don't you just use a label?

Offline mizzl

  • DTF.org Member
  • *
  • Posts: 1769
  • Gender: Male
  • I have officialy been ravenhearted. Thanks Zydar!
Re: Any java programmers? Simple question i have...
« Reply #3 on: March 07, 2011, 12:53:48 PM »
Why don't you just get a Mac?
Fixed for Harry

Offline tjanuranus

  • Posts: 2234
  • Gender: Male
Re: Any java programmers? Simple question i have...
« Reply #4 on: March 07, 2011, 12:59:07 PM »
Why don't you just use a label?

because i'm only on Chapter 4 and i don't know what that is.... =(

Offline tjanuranus

  • Posts: 2234
  • Gender: Male

Offline AcidLameLTE

  • Nae deal pal
  • DTF.org Alumni
  • ****
  • Posts: 11134
  • Gender: Male
Re: Any java programmers? Simple question i have...
« Reply #6 on: March 07, 2011, 01:02:10 PM »
To be fair, I didn't really look at your code. I just assumed you were making your own GUI :lol


Offline Durg

  • Posts: 1007
  • Gender: Male
  • Evil Java Genius & Horder of Open Source Software
Re: Any java programmers? Simple question i have...
« Reply #7 on: March 07, 2011, 01:17:26 PM »
Check to see if a % character was entered, input.indexOf("%")>-1, and strip it out, input.replaceAll("%","").  Then once you parse the number to double divide it by 100.
When I die, I want to go peacefully in my sleep just like my grandfather, and not like the screaming passengers in his car!

Offline tjanuranus

  • Posts: 2234
  • Gender: Male
Re: Any java programmers? Simple question i have...
« Reply #8 on: March 07, 2011, 01:19:44 PM »
i'm going to look into the suggestions you guys made. I haven't learned how to do them yet but i will try.

Offline Durg

  • Posts: 1007
  • Gender: Male
  • Evil Java Genius & Horder of Open Source Software
Re: Any java programmers? Simple question i have...
« Reply #9 on: March 07, 2011, 01:24:27 PM »
i'm going to look into the suggestions you guys made. I haven't learned how to do them yet but i will try.

Both methods are in the String class.

https://download.oracle.com/javase/1.5.0/docs/api/java/lang/String.html
When I die, I want to go peacefully in my sleep just like my grandfather, and not like the screaming passengers in his car!

Offline tjanuranus

  • Posts: 2234
  • Gender: Male
Re: Any java programmers? Simple question i have...
« Reply #10 on: March 07, 2011, 02:19:11 PM »
thanks i got it now. The problem is if someone enters something other than what i want the program crashes. Working on a way to fix of all this.

Offline tjanuranus

  • Posts: 2234
  • Gender: Male
Re: Any java programmers? Simple question i have...
« Reply #11 on: March 07, 2011, 02:33:45 PM »
ok this is what i finally put into the code. Note, i haven't learned exception handling or arrays yet or anything...

while (isInt == true)
      {
         input = JOptionPane.showInputDialog("Numbers only please.\n" +
                             "Enter the percentage of average daily population increase.");
         
         if (input == null || input.length() == 0)
         {
            isInt = false;
          
         }
          for (int i1 = 0; i1 < input.length(); i1++)
         {
                     //If we find a non-digit character we return false.
                     if (!Character.isDigit(input.charAt(i1)))
                         isInt = false;

         }

               if (isInt == true)
               {
                  percent = Double.parseDouble(input);
                  isInt = false;
               }
               else
               {
                  isInt = true;
               }
      }

Offline tjanuranus

  • Posts: 2234
  • Gender: Male
Re: Any java programmers? Simple question i have...
« Reply #12 on: March 07, 2011, 03:48:53 PM »
ok another issue i'm not sure why this is happening... This is supposed to convert celsius to fahrenheit. The conversion rate is 9/5 * Celsius + 32.

When i enter that it never works. It always shouls 9/5 as 1.0 instead of 1.8 which it actually is. So this code works...

                double fahr;      //Fahrenheit output
      int c;            //Celsius counting integer
      double calc = 1.8;   //Calculation
      
      System.out.println("Celsius      Fahrenheit.");
      System.out.println(".........................");
      
      for (c=0; c<= 20; c++)
      {
         fahr = calc * c + 32;
         
         System.out.printf(c + "\t\t" + "%.2f\n", fahr);
      }


but this code does not...

                double fahr;      //Fahrenheit output
      int c;            //Celsius counting integer
      
      System.out.println("Celsius      Fahrenheit.");
      System.out.println(".........................");
      
      for (c=0; c<= 20; c++)
      {
         fahr = 9/5 * c + 32;
         
         System.out.printf(c + "\t\t" + "%.2f\n", fahr);
      }

WHY????

Offline Fiery Winds

  • DTF.org Alumni
  • ****
  • Posts: 2959
  • Gender: Male
Re: Any java programmers? Simple question i have...
« Reply #13 on: March 07, 2011, 04:07:42 PM »
I think there's an issue when multiplying an int and a double that causes it to round to a whole number.

Offline tjanuranus

  • Posts: 2234
  • Gender: Male
Re: Any java programmers? Simple question i have...
« Reply #14 on: March 07, 2011, 04:14:46 PM »
made everything a double and still doesn't work properly...

                double fahr;      //Fahrenheit output
      double c;         //Celsius counting integer
      
      System.out.println("Celsius      Fahrenheit.");
      System.out.println(".........................");
      
      for (c=0; c<= 20; c++)
      {
         fahr = 9 / 5 * c + 32;
         
         System.out.printf(c + "\t\t" + "%.2f\n", fahr);
      }

Offline Fiery Winds

  • DTF.org Alumni
  • ****
  • Posts: 2959
  • Gender: Male
Re: Any java programmers? Simple question i have...
« Reply #15 on: March 07, 2011, 06:14:57 PM »
Ok, I think I figured it out. 

When writing "9/5" the default type is int literal, so it will give you an int literal as an answer, disregarding any remainder. 

Go back to your original code and write "9.0/5.0" and it should work (treats both numbers as double).

Offline tjanuranus

  • Posts: 2234
  • Gender: Male
Re: Any java programmers? Simple question i have...
« Reply #16 on: March 07, 2011, 06:30:09 PM »
thanks! That worked out well.

Offline Vivace

  • Posts: 664
  • Gender: Male
Re: Any java programmers? Simple question i have...
« Reply #17 on: March 08, 2011, 09:17:58 AM »
you need to pay more attention to what you are placing into your variables.

For example, an integer variable should not be holding strings. integer variables should not be holding doubles nor doubles holding integer variables and so on. If you are converting from one to another you need to be sure that you maintain value integrity while you make the conversion or you might lose information along the way. Take the following example

int x = 5;
double y = 1.5;
int z = 30;

Round((x * y) + z);

Now if we take the above statement as is we have Round((5*1.5) + 30). This becomes Round(37) or 37; Did you see what happened? 5 * 1.5 became 7 not 7.5. This is because we are multiplying an int and a double together and the decimal value is lost. This has happened to me a few times and it took a VERY long time to find out why my math was wrong. You need to make sure that x AND y are of the same type. Once you get a value THEN convert to whatever type you wish.

double x = 5.0;
double y = 1.5;
double z = 30.0;

Round((x * y) + z);

Now it should simplify to Round(37.5) which makes the Round do its job on a proper value.

you could also just do this: Round((toFloat(x) * y) + toFloat(z));

---

Tip #2. Never take an input from a user as an integer type unless you restrict him from typing anything in that isn't 0-9. Always return the inputted value into a string and work on it from there.

Hope this helps.  ;)
"What kind of Jedis are these? Guardians of peace and justice my ass!"

"Ha ha! You fool! My Kung Fu is also big for have been trained in your Jedi arts why not!"

Offline tjanuranus

  • Posts: 2234
  • Gender: Male
Re: Any java programmers? Simple question i have...
« Reply #18 on: March 08, 2011, 12:07:54 PM »
yes it does help. Like i said i am brand new to all of this so any advice is much appreciated. When you say take the input as a string you mean numeric input? I know when using JOptionPane it takes it as a string first but when you use scanner i always take the input and make it a double or int right away. Are you saying take the Scanner input as a string and then convert it?

Offline tjanuranus

  • Posts: 2234
  • Gender: Male
Re: Any java programmers? Simple question i have...
« Reply #19 on: March 08, 2011, 10:24:05 PM »
took my midterm today. If i don't get a 100 i will be pissed. I nailed that shit.

Offline Vivace

  • Posts: 664
  • Gender: Male
Re: Any java programmers? Simple question i have...
« Reply #20 on: March 09, 2011, 04:07:01 AM »
yes it does help. Like i said i am brand new to all of this so any advice is much appreciated. When you say take the input as a string you mean numeric input? I know when using JOptionPane it takes it as a string first but when you use scanner i always take the input and make it a double or int right away. Are you saying take the Scanner input as a string and then convert it?

any user input should be taken in as a string and then converted later on for whatever you plan to use it for. This avoids the very pitfalls you have run into. ;)
"What kind of Jedis are these? Guardians of peace and justice my ass!"

"Ha ha! You fool! My Kung Fu is also big for have been trained in your Jedi arts why not!"

Offline tjanuranus

  • Posts: 2234
  • Gender: Male
Re: Any java programmers? Simple question i have...
« Reply #21 on: March 22, 2011, 03:04:13 AM »
ok been practicing what you said about almost inputing as string. If anyone could take a look at this and tell me if there is a simpler way to do this input validation i would be most grateful!

import java.util.Scanner;

public class tests
{
   public static void main(String[] args)
   {
      String input;                  //User's string input
      double number = 0;               //Test score input
      int out = 0, sat = 0, unsat = 0;   //type of scores
      boolean isInt = false;            //Boolean for testing
      
      Scanner keyboard = new Scanner(System.in);
      
      while (isInt == false)
      {
         System.out.println("Enter a test score or 101 to quit: ");
         input = keyboard.nextLine();
         
         //Call the input validation method
            isInt = isParsableToInt(input);
            if (isInt == true)
               number = Integer.parseInt(input);
      }
      
      
      while (number <0 || number >101)
      {
         System.out.println("Number must be between 0 and 101. enter again");
         input = keyboard.nextLine();
         
         //Call the input validation method
            isInt = isParsableToInt(input);
            if (isInt == true)
               number = Integer.parseInt(input);
         
      }
      while (number != 101)
      {
         if (number >= 90 && number <= 100)
            out++;
         else if (number >= 70 && number <= 89)
            sat++;
         else if (number >= 0 && number <= 69)
            unsat++;
         
         isInt = false;
         
         while (isInt == false)
         {
            System.out.println("Enter a test score or 101 to quit: ");
            input = keyboard.nextLine();
            
            //Call the input validation method
               isInt = isParsableToInt(input);
               if (isInt == true)
                  number = Integer.parseInt(input);
         }
         
         while (number <0 || number >101)
         {
            System.out.println("Number must be between 0 and 101. enter again");
            input = keyboard.nextLine();
            
            //Call the input validation method
               isInt = isParsableToInt(input);
               if (isInt == true)
                  number = Integer.parseInt(input);
         }
      }
      System.out.println("Number of outsanding scores\tSatisfactory scores\t" +
      "Unsatisfactory scores");
      System.out.println("..................................................." +
                     ".........................");
      System.out.println(out + "\t\t\t\t" + sat + "\t\t\t" + unsat);
   }
      //Input Validation Method
      public static boolean isParsableToInt(String k)
      {
         try
         {
            Integer.parseInt(k);
            return true;
         }
            catch(NumberFormatException nfe)
            {
               return false;
            }
      }
}



Offline tjanuranus

  • Posts: 2234
  • Gender: Male
Re: Any java programmers? Simple question i have...
« Reply #22 on: March 22, 2011, 03:04:37 AM »
code doesn't paste well in here but you get the idea!

Offline AcidLameLTE

  • Nae deal pal
  • DTF.org Alumni
  • ****
  • Posts: 11134
  • Gender: Male
Re: Any java programmers? Simple question i have...
« Reply #23 on: March 22, 2011, 04:10:59 AM »
I haven't had a look at your code (I've only just woken up and I'm too tired to be reading Java right now) but if you want to post your code so that it's formatted, try using this website:

https://pastebin.com/

It has syntax highlighting for Java and loads of other languages.

Offline Vivace

  • Posts: 664
  • Gender: Male
Re: Any java programmers? Simple question i have...
« Reply #24 on: March 22, 2011, 06:53:53 AM »
You should try to do all your validation in a single method. Here's an idea with pseudo-code

while(GetUserinput())
if(ValidateUserInput(input) is true) then
 WorkOnUserInput(input)
else
 print error

Hope this helps.
"What kind of Jedis are these? Guardians of peace and justice my ass!"

"Ha ha! You fool! My Kung Fu is also big for have been trained in your Jedi arts why not!"

Offline tjanuranus

  • Posts: 2234
  • Gender: Male
Re: Any java programmers? Simple question i have...
« Reply #25 on: March 23, 2011, 02:42:36 AM »
You should try to do all your validation in a single method. Here's an idea with pseudo-code

while(GetUserinput())
if(ValidateUserInput(input) is true) then
 WorkOnUserInput(input)
else
 print error

Hope this helps.

ok going to try it out. Thanks!

Offline tjanuranus

  • Posts: 2234
  • Gender: Male
Re: Any java programmers? Simple question i have...
« Reply #26 on: March 25, 2011, 08:30:11 PM »
so i took your advice and have now been doing everything with String first. heres what just worked on. Shit took a while!

So this is the most complicated thing i've done with no help! I know it's simple to some of you guys but i think i'm getting the hang of things. Didn't use the book for any references..

Text is out of place in here but you get the idea. About 5 chapters worth of knowledge used in this program. Starting chapter 6 next.


import java.util.Scanner;
import java.text.DecimalFormat;

public class ConversionProgram
{
   public static void main(String[] args)
   {
      String input;            //Get users scanner input in string format
      double distance = 0;      //Convert input to double for distance
      int number = 0;            //Convert input for converting options
      boolean isInt = false;      //Boolean for testing input validation
      
      Scanner keyboard = new Scanner(System.in);
      
      while (isInt == false)
      {
         //Get user input and convert to double
         System.out.println("Enter the distance in meters");
         input = keyboard.nextLine();
         
         //Call the input validation method
           isInt = isParsableToDouble(input);
           if (isInt == true)
              distance = Double.parseDouble(input);
      }
         isInt = false;
      //Input validation, no negative numbers
      while (distance < 0)
      {
         while (isInt == false)
         {
            System.out.println("Distance cannot be negative. Enter a positive number.");
            input = keyboard.nextLine();

            //Call the input validation method
               isInt = isParsableToDouble(input);
               if (isInt == true)
                  distance = Double.parseDouble(input);
         }
      }
      
      do
      {   
         number = menu(number);
         
            switch (number)
            {
               case 1: showKilometers(distance);
                     break;
               case 2: showInches(distance);
                     break;
               case 3: showFeet(distance);
                     break;
            }
         
      }while (number != 4);
      
      System.out.println("Thank you for using this program!");
   }
   //Input Validation Method Double
   public static boolean isParsableToDouble(String d)
   {
      try
      {
         Double.parseDouble(d);
         return true;
      }
       catch(NumberFormatException nfe)
       {
          return false;
       }
   }
   //Input Validation Method Int
   public static boolean isParsableToInt(String k)
   {
      try
      {
         Integer.parseInt(k);
         return true;
      }
       catch(NumberFormatException nfe)
       {
          return false;
       }
   }
   public static void showKilometers(double meters)
   {
      DecimalFormat fmt = new DecimalFormat("0.0000");
      double kilo = meters * .001;
      if (kilo != 1)
      {
      System.out.println("The distance converts to " + fmt.format(kilo) + " Kilometers.");
      System.out.println("");
      }
      else
         System.out.println("The distance converts to " + kilo + " Kilometer.");
         System.out.println("");
   }
   public static void showInches(double meters)
   {
      DecimalFormat fmt = new DecimalFormat("0.0000");
      double inches = meters * 39.37;
      if (inches != 1)
      {
         System.out.println("The distance converts to " + fmt.format(inches) + " Inches.");
         System.out.println("");
      }
      else
         System.out.println("The distance converts to " + inches + " Inch.");
         System.out.println("");
   }
   public static void showFeet(double meters)
   {
      DecimalFormat fmt = new DecimalFormat("0.00");
      double feet = meters * 3.281;
      if (feet != 1)
      {
         System.out.println("The distance converts to " + fmt.format(feet) + " Feet.");
         System.out.println("");
      }
      else
         System.out.println("The distance converts to " + feet + " Foot.");
         System.out.println("");
   }
   public static int menu(int i)
   {
      String input;
      boolean isInt = false;
      int number = 0;
      
      Scanner keyboard = new Scanner(System.in);
      while (isInt == false)
      {   
         
         System.out.println("What unit(s) of measurement would you like that converted to?");
         System.out.println("Enter 1 for Kilometers");
         System.out.println("Enter 2 for Inches");
         System.out.println("Enter 3 for Feet");
         System.out.println("Enter 4 to quit.");
         input = keyboard.nextLine();
         
         //Call the input validation method
           isInt = isParsableToInt(input);
           if (isInt == true)
              number = Integer.parseInt(input);
           
      }
         isInt = false;
      while (number < 1 || number > 4)
      {
         
         while (isInt == false)
         {
            System.out.println("Entry must be between 1 and 4. Enter again.");
            input = keyboard.nextLine();
            
            //Call the input validation method
              isInt = isParsableToInt(input);
              if (isInt == true)
                 number = Integer.parseInt(input);
         }
      }
         return number;
      
   }
}
/** Resulting output tests...

Enter the distance in meters
-1
Distance cannot be negative. Enter a positive number.
546.78
What unit(s) of measurement would you like that converted to?
Enter 1 for Kilometers
Enter 2 for Inches
Enter 3 for Feet
Enter 4 to quit.
1
The distance converts to 0.5468 Kilometers.


What unit(s) of measurement would you like that converted to?
Enter 1 for Kilometers
Enter 2 for Inches
Enter 3 for Feet
Enter 4 to quit.
2
The distance converts to 21526.7286 Inches.


What unit(s) of measurement would you like that converted to?
Enter 1 for Kilometers
Enter 2 for Inches
Enter 3 for Feet
Enter 4 to quit.
3
The distance converts to 1793.99 Feet.


What unit(s) of measurement would you like that converted to?
Enter 1 for Kilometers
Enter 2 for Inches
Enter 3 for Feet
Enter 4 to quit.
5
Entry must be between 1 and 4. Enter again.
a
Entry must be between 1 and 4. Enter again.
.eoa.ef
Entry must be between 1 and 4. Enter again.
4
Thank you of using this program!

*/

Offline Vivace

  • Posts: 664
  • Gender: Male
Re: Any java programmers? Simple question i have...
« Reply #27 on: March 26, 2011, 01:38:58 AM »
I just did a cursory glance but, "excellent".

Nice use of methods. When you learn about objects you will begin to understand how you could make such a program even more intuitive and powerful. But for now, you can only work with the knowledge you have. One thing and it's not that's wrong but it's another way to do something

if(isParsableToInt(inputStr) == true)

can also be written as

if(isParsableToInt(inputStr))

True is represented as 1 and False as 0. Thus when you return True, you are really just returning 1. If you return False you are returning 0. ;) To represent the above to check for false you would write

if(!isParsableToInt(inputStr))

To read out the top you would go, "if not parseable to int then...". therefore the if statement will get run if the string is NOT an integer value. ;) The "!" just takes the opposite approach to such a statement. 
"What kind of Jedis are these? Guardians of peace and justice my ass!"

"Ha ha! You fool! My Kung Fu is also big for have been trained in your Jedi arts why not!"

Offline tjanuranus

  • Posts: 2234
  • Gender: Male
Re: Any java programmers? Simple question i have...
« Reply #28 on: April 05, 2011, 04:32:44 AM »
thanks for the help as always. I'm stuck on this problem and i don't know why this isn't working. This is my first time using array's so that's probably why i don't know what i am doing but here it is..

The problem lies when calling the getHighest and getLowest method. The error i get is..

The method getHighest(double[]) in the type RainfallClass is not applicable for the arguments ()

import java.util.Scanner;
import java.text.DecimalFormat;

public class RainfallClass
{
   public static void main(String[] args)
   {
      DecimalFormat fmt = new DecimalFormat("0.00");
      
      //call the getTotal method
      double tot = getTotal();
      
      //call and pass the average method
      double average = getAverage(tot);
      
      //Call and pass the highest method
      double highest = getHighest();
      
      //Call and pass the lowest method
      double lowest = getLowest();
      
      //Display output
      System.out.println("Total\t\tAverage\t\tHighest\t\tLowest");
      System.out.println("..........................................................");
      System.out.println(fmt.format(tot) + " inches \t" + fmt.format(average) + " inches \t"
                     + fmt.format(highest) + " inches\t" + fmt.format(lowest) + " inches");
         
   }
   public static double getTotal()
   {
      
      double total = 0.0;
      double[] inches = new double[12];
      String[] months = {"January", "February", "March", "April", "May",
                     "June", "July", "August", "September", "October",
                     "November", "December"};
      
      Scanner keyboard = new Scanner(System.in);
      
      for (int i = 0; i < inches.length; i++)
      {
         System.out.println("Enter the total rainfall for " + months);
         inches = keyboard.nextDouble();
         keyboard.nextLine();
            while (inches < 0)
            {   
               System.out.println("Entry must be a postive number");
               System.out.println("Enter the total rainfall for " + months);
               inches = keyboard.nextDouble();
               keyboard.nextLine();
            }
         total += inches;
      }
      getHighest(inches);
      getLowest(inches);
      return total;
   }
   public static double getAverage(double a)
   {
      double average = a / 12;
      return average;
      
   }
   public static double getHighest(double[] h)
   {
      double highest = h[0];
      
      for (int j = 0; j < h.length; j++)
      {
         if (h[j] > highest)
            highest = h[j];
      }
      
      return highest;
   }
   public static double getLowest(double[] l)
   {
      double lowest = l[0];
      
      for (int j = 0; j < l.length; j++)
      {
         if (l[j] < lowest)
            lowest = l[j];
      }
      
      return lowest;
      
      
   }
}

Offline Durg

  • Posts: 1007
  • Gender: Male
  • Evil Java Genius & Horder of Open Source Software
Re: Any java programmers? Simple question i have...
« Reply #29 on: April 05, 2011, 06:45:34 AM »
You are supposed to pass the Double array into getHighest but you don't have a double array.  Where are you supposed to get the double array from?  Command line arguments maybe?


Edit:  OK.  I see.  getTotal() is loading the array inches and returning the total.  The problem with this is that you lose the inches array once you leave getTotal.  Probably the easiest thing to do is make inches a class variable.  Then you don't have to call getHighest from the getTotal method.  Also, if you make inches a class variable you don't have to pass it into the getHighest method as an argument.
« Last Edit: April 05, 2011, 06:51:17 AM by Durg »
When I die, I want to go peacefully in my sleep just like my grandfather, and not like the screaming passengers in his car!

Offline Durg

  • Posts: 1007
  • Gender: Male
  • Evil Java Genius & Horder of Open Source Software
Re: Any java programmers? Simple question i have...
« Reply #30 on: April 05, 2011, 06:58:10 AM »
Probably a cleaner way to do it is this, in pseudo code.

main
{
load inches[]
load months[]

call getTotal with inches and return total
call getAverage with inches and return average
call getLowest with inches and return lowest
call getHighest with inches and return highest

print it all out
}

the other methods would follow.

It really doesn't make since to load inches in the getTotal method since, based on it's name it's only job should be to getting the total.
When I die, I want to go peacefully in my sleep just like my grandfather, and not like the screaming passengers in his car!

Offline tjanuranus

  • Posts: 2234
  • Gender: Male
Re: Any java programmers? Simple question i have...
« Reply #31 on: April 05, 2011, 07:56:18 AM »
ok your sudo code really helped! Like i said this is the first thing i've done involving arrays so yeah.. Here is the code i ended up with that works.

Code: [Select]
import java.util.Scanner;
import java.text.DecimalFormat;

public class RainfallClass2
{
public static void main(String[] args)
{
DecimalFormat fmt = new DecimalFormat("0.00");

double[] inches = new double[12];
String[] months = {"January", "February", "March", "April", "May",
"June", "July", "August", "September", "October",
"November", "December"};

Scanner keyboard = new Scanner(System.in);

for (int i = 0; i < inches.length; i++)
{
System.out.println("Enter the total rainfall for " + months[i]);
inches[i] = keyboard.nextDouble();
keyboard.nextLine();
while (inches[i] < 0)
{
System.out.println("Entry must be a postive number");
System.out.println("Enter the total rainfall for " + months[i]);
inches[i] = keyboard.nextDouble();
keyboard.nextLine();
}

}


//call the getTotal method
double tot = getTotal(inches);

//call and pass the average method
double average = getAverage(tot);

//Call and pass the highest method
double highest = getHighest(inches);

//Call and pass the lowest method
double lowest = getLowest(inches);

//Display output
System.out.println("Total\t\tAverage\t\tHighest\t\tLowest");
System.out.println("..........................................................");
System.out.println(fmt.format(tot) + " inches \t" + fmt.format(average) + " inches \t"
+ fmt.format(highest) + " inches\t" + fmt.format(lowest) + " inches");

}
public static double getTotal(double[] t)
{

double total = t[0];

for (int i = 1; i < t.length; i++)
total += t[i];

return total;
}
public static double getAverage(double a)
{
double average = a / 12;
return average;

}
public static double getHighest(double[] h)
{
double highest = h[0];

for (int j = 0; j < h.length; j++)
{
if (h[j] > highest)
highest = h[j];
}

return highest;
}
public static double getLowest(double[] l)
{
double lowest = l[0];

for (int j = 0; j < l.length; j++)
{
if (l[j] < lowest)
lowest = l[j];
}

return lowest;


}
}

Offline Durg

  • Posts: 1007
  • Gender: Male
  • Evil Java Genius & Horder of Open Source Software
Re: Any java programmers? Simple question i have...
« Reply #32 on: April 05, 2011, 09:24:14 AM »
 :tup

That looks better.
When I die, I want to go peacefully in my sleep just like my grandfather, and not like the screaming passengers in his car!

Offline tjanuranus

  • Posts: 2234
  • Gender: Male
Re: Any java programmers? Simple question i have...
« Reply #33 on: April 27, 2011, 01:20:05 AM »
Ok staring at this for hours and stumped! Any idea why i'm getting an error at the line... panel[p].add(label[p]);????????????
Exception in thread "main" java.lang.NullPointerException
   at TravelExpenses.<init>(TravelExpenses.java:49)
   at TravelExpenses.main(TravelExpenses.java:130)
Code: [Select]
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.text.*;

public class TravelExpenses extends JFrame
{
private JPanel[] panel = new JPanel[8];
private JLabel[] label = new JLabel[8];
private JTextField[] text = new JTextField[8];
private JButton calc;
private final int WIDTH = 500;
private final int HEIGHT = 500;

//Create constructor
public TravelExpenses()
{
//Set the frame title
setTitle("Travel Expense Calculator");
//Set the size of the frame
setSize(WIDTH, HEIGHT);
//Exit on close
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Set grid layout
setLayout(new GridLayout(4, 3));

//Create labels
label[0] = new JLabel("Number of days on trip.");
label[1] = new JLabel("Amount of airfare.");
label[2] = new JLabel("Car rental fees.");
label[3] = new JLabel("Miles driven if a private vehicle was used.");
label[4] = new JLabel("Amount of parking fees.");
label[5] = new JLabel("Taxi charges.");
label[6] = new JLabel("Conference or seminar registration fees.");
label[7] = new JLabel("Lodging charges per night.");
//Create text fields for each label using for loop.
for (int i = 0; i < text.length; i++)
{
text[i] = new JTextField(4);
}
//Create Calculate button
calc = new JButton("Calculate.");
//Add action listener to button.
calc.addActionListener(new CalcButtonListener());

//Add labels to panels
for (int p = 0; p < label.length; p++)
{
panel[p].add(label[p]);
}
panel[8].setLayout(new BorderLayout());

//Add text and labels to the panel using for loop
for (int j = 0; j < text.length; j++)
{
panel[j].add(text[j]);
}
panel[8].add(calc, BorderLayout.SOUTH);
for (int k = 0; k < panel.length; k++)
{
add(panel[k]);
}
//Display frame
setVisible(true);
}
//Create CalcButton Listener Class
public class CalcButtonListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
String input; //For getting text field input
//Create a double array for conversion
double[] n = new double[8];
double total = 0.0, excess, totalR = 0.0, lodging;
//Reimbursement totals array.
double[] r = new double[5];

//Create for loop to convert string to double
for (int i = 0; i < text.length; i++)
{
//Get user input
input = text[i].getText();
//Convert input to double
n[i] = Double.parseDouble(input);
}
//Reimbursement totals
r[0] = n[0] * 37.00;
r[1] = n[0] * 10.00;
r[2] = n[0] * 20.00;
r[3] = n[0] * 95.00;
r[4] = n[3] * 0.27;

//Lodging amount
lodging = n[0] * n[7];

//Total expenses incurred by the business person
total = (n[1] + n[2] + n[3] + n[4] + n[5] + n[6]) + lodging;
//Total Reimbursements allowed
for (int k = 0; k < r.length; k++)
{
totalR += r[k];
}
//Calculate excess amount
excess = total - totalR;

//Create decimal format object
DecimalFormat fmt = new DecimalFormat("#,##0.00");
//Display total expenses incurred
JOptionPane.showMessageDialog(null, "The total expenses incurred is $" +
fmt.format(total));
//Display total allowable expenses for the trip
JOptionPane.showMessageDialog(null, "The total allowable expenses is $" +
fmt.format(totalR));
//Display excess or savings
if (excess > 0)
{
JOptionPane.showMessageDialog(null, "The total expenses that must be " +
  "paid by the business person is $" +
  fmt.format(excess));
}
else
{
excess = excess * -1;
JOptionPane.showMessageDialog(null, "The amount saved by the business " +
"person is $" + fmt.format(excess));
}
}
}
public static void main(String[] args)
{
new TravelExpenses();
}

}
« Last Edit: April 27, 2011, 01:48:55 AM by tjanuranus »

Offline Durg

  • Posts: 1007
  • Gender: Male
  • Evil Java Genius & Horder of Open Source Software
Re: Any java programmers? Simple question i have...
« Reply #34 on: April 27, 2011, 06:26:27 AM »
Ah the old NullPointerException.  I get these literally, on average, twice a day.   :facepalm:

Quote
Ok staring at this for hours and stumped! Any idea why i'm getting an error at the line... panel[p].add(label[p]);

Yeah.  You know how you had to create 8 new JLabel for the label array?  You have to do the same for your panel array.  panel[p] is null
When I die, I want to go peacefully in my sleep just like my grandfather, and not like the screaming passengers in his car!