Results 1 to 11 of 11
Like Tree3Likes
  • 1 Post By pbrockway2
  • 1 Post By pbrockway2
  • 1 Post By Tolls

Thread: Need help

  1. #1
    alkash89 is offline Member
    Join Date
    Oct 2012
    Posts
    2
    Rep Power
    0

    Default Need help

    hey guys im in this programming class and basically this is a very simple task. they ask you to ask the User what internet package they are using and then calculate how much money the user will owe after they input what type of package and how many hours they used it. I have the code written out here:
    Java Code:
    import java.util.Scanner;
    public class Lab2 
    
    {
      public static void main(String[] args)
      {
        String packageType;
    	float hoursUsed;
    	double totalDue ;
    	
    	Scanner keyboard = new Scanner (System.in);
    	System.out.print("Enter package type (A, B, or C): ");
    	packageType = keyboard.nextLine();
    	char mainChar= packageType.charAt(0);
    	if (mainChar == 'A' || mainChar == 'a' )
    	{ 
    	  System.out.print("Enter number of hours: ");
    	  hoursUsed = keyboard.nextInt();
    	  if (hoursUsed>=0 && hoursUsed <=10)
    	  {		
    	    totalDue = 9.95 ;
    		System.out.println("Total due: " + totalDue + "$");
    	  }
    	  else if(hoursUsed > 10 && hoursUsed <= 744)
    	  {
    	    totalDue = (9.95* hoursUsed);
    	    System.out.println("Total Due: " + totalDue + "$");
    	  }
    	  else if(hoursUsed <0)
    		System.out.print("Hours connot be negative.");
    	  else if(hoursUsed > 744)
    		System.out.print("Invalid input. Hours cannot exceed 744");
    	}
    	else if(mainChar == 'B' || mainChar == 'b')
    	{
    	  System.out.print("Enter number of hours: ");
    	  hoursUsed = keyboard.nextInt();
    	  if (hoursUsed>=0 && hoursUsed <=20)
    	  {
    	    totalDue = 13.95;
    		System.out.println("Total due: " + totalDue + "$");
    	  }
    	  else if (hoursUsed > 20 && hoursUsed <= 744)
    	  {
    		totalDue = (9.95* hoursUsed);
    		System.out.println("Total Due: " + totalDue + "$");
    	  }
    	  else if(hoursUsed <0)
    		System.out.print("Hours connot be negative.");
    	  else if(hoursUsed > 744)
    		System.out.print("Invalid input. Hours cannot exceed 744");
    	  else if (mainChar == 'C' || mainChar == 'c')
    	  {
    	    System.out.print("Enter number of hours: ");
    	    hoursUsed = keyboard.nextInt();
    	    if (hoursUsed >= 0 || hoursUsed <= 744)
    	    {
    		  totalDue= 19.95;
    	  	  System.out.println("Total due: " +totalDue + "$");
    	    }
    	    else if(hoursUsed <0)
    	      System.out.print("Hours connot be negative.");
    	    else if(hoursUsed > 744)
    	      System.out.print("Invalid input. Hours cannot exceed 744");  
    	  }
    	}
    		else
    		  System.out.println("Invalid package type");
    	
      }
    }
    I need to figure out how to limit the user in a way that if he types package Ab for example it will give them an error. Please help
    Last edited by pbrockway2; 10-17-2012 at 11:21 PM. Reason: code tags added

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

    Default Re: Need help

    Hi alkash89, welcome to the forums!

    I have added "code" tags to your post. The idea is that you put [code] at the start of any code and [/code] at the end: that way the formatting is preserved by the forum software and the code is readable.
    alkash89 likes this.

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

    Default Re: Need help

    You could check the length of the packageType string and if it is greater than one produce the error.

    You don't actually say what should happen after this error is produced. If your intention is that the program should ask them to renter the package type, then I think it would be a good idea to write a separate method to obtain the package type. This method would prompt the user, get their response, check the length and the first character. It could do all this within a loop, and keep going until the user enters a valid, single character.

    Putting such a loop within the main() method would be possible, but the main() method is already too long and splitting things up into multiple methods ("one method does one thing") would make the code clearer.

  4. #4
    alkash89 is offline Member
    Join Date
    Oct 2012
    Posts
    2
    Rep Power
    0

    Default Re: Need help

    Thanks, that makes sense we just have not gone over any of that in class, and i'm pretty sure the professor is against using anything that he has not taught. Pretty lame i know...

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

    Default Re: Need help

    No - you have to attack things in some order or other. It can be done without a second method.

    If all you want to do is spit out an error message if the user enters "Ab" then just check the length of that string to see if it is greater than 1. The String API docs list all the string methods including the charAt() you are already using.

  6. #6
    penguinCoder is offline Member
    Join Date
    Oct 2012
    Location
    Tempe, Arizona
    Posts
    77
    Blog Entries
    12
    Rep Power
    0

    Default Re: Need help

    I like optimizing code far more then answering questions, so let me start off with some techniques that would let you optimize the code you have written.

    Where you have:
    Java Code:
    if(mainChar == 'A' || mainChar == 'a')
    You could use the method .toLowerCase() or .toUpperCase() to check both of these without using a logic 'or'.
    Java Code:
    if(mainChar.toLowerCase() == 'a')
    Would do the same thing, and in my opinion is a little simpler.


    Where you have:
    Java Code:
    totalDue = 9.95;
    System.out.println("Total Due: " + totalDue + "$");
    Since you don't use totalDue anywhere else within the program, you could save yourself some memory just by sticking the value right into the print statement.
    Java Code:
    System.out.println("Total Due: $9.95");

    Where you have:
    Java Code:
    if (hoursUsed>=0 && hoursUsed <=10)
    {    
    totalDue = 9.95 ;
    System.out.println("Total due: " + totalDue + "$");
    }
    else if(hoursUsed > 10 && hoursUsed <= 744)
    {
    totalDue = (9.95* hoursUsed);
    System.out.println("Total Due: " + totalDue + "$");
    }
    else if(hoursUsed <0)
    System.out.print("Hours connot be negative.");
    else if(hoursUsed > 744)
    System.out.print("Invalid input. Hours cannot exceed 744");
    You could use just one condition in all of your if statements by writing it in a more correct order like:
    Java Code:
    if(hoursUsed<0)
      ..code..
    else if(hoursUsed<=10)
      ..code..
    else if(hoursUsed<744)
      ..code..
    else
      ..code..
    This makes it a lot easier to look at, and a lot simpler to write.


    After your question is answered about validating what the user inputs, where you have:
    Java Code:
    else if (mainChar == 'C' || mainChar == 'c')
    Can be switched to just an:
    Java Code:
    else
    Seeing as it will not be able to get to the if statements unless the user enters an A, B or C.


    Now on to your actual question, validating the user input. Where you have:
    Java Code:
    System.out.print("Enter package type (A, B, or C): ");
    packageType = keyboard.nextLine();
    char mainChar= packageType.charAt(0);
    Is there a reason that you first save it into a string, and then convert it into a character? You could save yourself about 2 bytes of memory if you just did:
    Java Code:
    System.out.print("Enter package type (A, B, or C): ");
    char mainChar= keyboard.next().charAt(0);
    For validating the user input, just put a do while loop around the whole statement, and let it keep repeating if the input does not equal A, B OR C. I would also throw a if statement into the loop, and have that display your:
    Java Code:
    else
    System.out.println("Invalid package type");
    If the input does not equal A, B OR C.


    That all said, it is quite refreshing to read your code; as most people who post on this site do not use formatting as well as your do. Not trying to be hyper-critical in my post, just a bunch of FYI stuff for your future in programming. If you have any questions about any of it, please post. Several of my suggestions can be used in multiple places throughout the code.

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

    Default Re: Need help

    Please find and go through the Forum Rules -- particularly the third paragraph.

    db
    If you're forever cleaning cobwebs, it's time to get rid of the spiders.

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

    Default Re: Need help

    Quote Originally Posted by penguinCoder View Post
    I like optimizing code far more then answering questions, so let me start off with some techniques that would let you optimize the code you have written.

    Where you have:
    Java Code:
    if(mainChar == 'A' || mainChar == 'a')
    You could use the method .toLowerCase() or .toUpperCase() to check both of these without using a logic 'or'.
    Java Code:
    if(mainChar.toLowerCase() == 'a')
    Would do the same thing, and in my opinion is a little simpler.
    I agree it reads better, however it is in no way a case of optimisation.
    The compiler will be producing a Character object (to be fair, it'll be using a pre-existing one) and then calling the toLowerCase() method on it.

    Quote Originally Posted by penguinCoder View Post
    Where you have:
    Java Code:
    if (hoursUsed>=0 && hoursUsed <=10)
    {    
    totalDue = 9.95 ;
    System.out.println("Total due: " + totalDue + "$");
    }
    else if(hoursUsed > 10 && hoursUsed <= 744)
    {
    totalDue = (9.95* hoursUsed);
    System.out.println("Total Due: " + totalDue + "$");
    }
    else if(hoursUsed <0)
    System.out.print("Hours connot be negative.");
    else if(hoursUsed > 744)
    System.out.print("Invalid input. Hours cannot exceed 744");
    You could use just one condition in all of your if statements by writing it in a more correct order like:
    Java Code:
    if(hoursUsed<0)
      ..code..
    else if(hoursUsed<=10)
      ..code..
    else if(hoursUsed<744)
      ..code..
    else
      ..code..
    This makes it a lot easier to look at, and a lot simpler to write.
    Close.
    Java Code:
    else if(hoursUsed<=744)
    :)

    But again, that's a legibility thing.
    I doubt it would make any practical difference, and may be worse if the most common range of values is between 0 and 10.
    Similarly here:

    Quote Originally Posted by penguinCoder View Post
    Is there a reason that you first save it into a string, and then convert it into a character? You could save yourself about 2 bytes of memory if you just did:
    Java Code:
     
    System.out.print("Enter package type (A, B, or C): ");
    char mainChar= keyboard.next().charAt(0);
    That's not actually saving anything, apart from a reference on the stack (which is rarely worth worrying about).
    The String already exists in the heap (created in the next() method, or more likely in the Scanner buffer somewhere).

    Premature optimisation is the root of all evil...:)
    Keep it legible, and let the compiler do its thing.
    Please do not ask for code as refusal often offends.

    ** This space for rent **

  9. #9
    penguinCoder is offline Member
    Join Date
    Oct 2012
    Location
    Tempe, Arizona
    Posts
    77
    Blog Entries
    12
    Rep Power
    0

    Default Re: Need help

    Quote Originally Posted by Tolls View Post
    But again, that's a legibility thing.
    I doubt it would make any practical difference, and may be worse if the most common range of values is between 0 and 10.
    Even if the common case were to be between 0-10, it would still have to calculate 2 comparisons, which would be even with how it was written. In the worst case scenario, instead of doing 7 comparisons, it would be doing 3, so I feel that is more optimized; especially as optimization is judged by worst case scenarios by default.

    Quote Originally Posted by Tolls View Post
    The String already exists in the heap (created in the next() method, or more likely in the Scanner buffer somewhere).
    You are saying that 'char s = keyboard.next().charAt(0)' creates a String? Not trying to offend, but you mind providing a link for this? Could not find anything via my own search of this...


    Does Java have something comparable to C++'s sizeOf function?
    Catching exceptions is for communists

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

    Default Re: Need help

    (penguin) Even if the common case were to be between 0-10, it would still have to calculate 2 comparisons, which would be even with how it was written. In the worst case scenario, instead of doing 7 comparisons, it would be doing 3, so I feel that is more optimized;
    My understanding is that the compiler is free to work whatever (valid) magic it likes, including magic that depends on what it observes to be happening repeatedly at runtime. So I don't see how you can go from code to knowing how many comparisons will take place.

    What really makes optimisation a bit dubious here is the context in which it is happening. There's user input going on at a glacial pace compared with everything else. Sure, "watch the pennies" etc, and those nanoseconds do mount up: but over the human lifetime of a user (enslaved to work 24/7 running the program) the best optimisation might give them, as reward for a lifetime of labour, a reprieve of maybe 30s (*).

    (* I haven't done the sums. And, as suggested, they possibly can't be done. But the point is that any "savings" ought to be considered relative to the slowest temporal link in the chain.)

    (Tolls) But again, that's a legibility thing.
    I agree, and that's why penguin's proposed changes are good ones.

    ---

    @OP: Way back I suggested checking the length of the input string to determine whether invalid strings (as distinct from invalid starting characters) were being entered. If you still have a problem you ought to post back.
    Fubarable likes this.

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

    Default Re: Need help

    Quote Originally Posted by penguinCoder View Post
    Even if the common case were to be between 0-10, it would still have to calculate 2 comparisons, which would be even with how it was written. In the worst case scenario, instead of doing 7 comparisons, it would be doing 3, so I feel that is more optimized; especially as optimization is judged by worst case scenarios by default.
    Apart from the compiler magic at runtime that pbrockway mentions, optimisation is judged by actual runtime usage. Which is why premature optimisation is (beyond some standard coding practices) pointless. You optimise by taking actual performance data, not by guessing at what might be a worst case scenario. How databases optimise searches is a good place to look, where a different balance of data will result in very different plans (ie code) for searching.

    Not that this is an extreme case, but I wanted to mention that how optimised your change is (and it is more legible, so I would write it like that anyway) is entirely down to the data passing through the system.

    Quote Originally Posted by penguinCoder View Post
    You are saying that 'char s = keyboard.next().charAt(0)' creates a String? Not trying to offend, but you mind providing a link for this? Could not find anything via my own search of this...
    Scanner.next() returns a String reference. That String is from the buffer.
    It already exists on the heap.
    All the original code was doing was assigning that reference to a local variable, it wasn't creating a new String.
    Here's the code:
    Java Code:
        public String next() {
            ensureOpen();
            clearCaches();
            
            while (true) {
                // The next line is grabbing the String token...this is what's returned.
                String token = getCompleteTokenInBuffer(null);
                if (token != null) {
                    matchValid = true;
                    skipped = false;
                    return token;
                }
                if (needInput)
                    readInput();
                else
                    throwFor();
            }
        }
    Quote Originally Posted by penguinCoder View Post
    Does Java have something comparable to C++'s sizeOf function?
    No.
    We tend to look a the system as a whole, rather than small individual bits, so heap dumps, and then see what's taking up the space.
    Fubarable likes this.
    Please do not ask for code as refusal often offends.

    ** This space for rent **

Posting Permissions

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