Results 1 to 11 of 11
Thread: Need help
- 10-17-2012, 11:17 PM #1
Member
- Join Date
- Oct 2012
- Posts
- 2
- Rep Power
- 0
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:
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 helpJava 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"); } }Last edited by pbrockway2; 10-17-2012 at 11:21 PM. Reason: code tags added
- 10-17-2012, 11:23 PM #2
Moderator
- Join Date
- Feb 2009
- Location
- New Zealand
- Posts
- 4,547
- Rep Power
- 11
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.
- 10-17-2012, 11:28 PM #3
Moderator
- Join Date
- Feb 2009
- Location
- New Zealand
- Posts
- 4,547
- Rep Power
- 11
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.
- 10-17-2012, 11:39 PM #4
Member
- Join Date
- Oct 2012
- Posts
- 2
- Rep Power
- 0
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...
- 10-17-2012, 11:53 PM #5
Moderator
- Join Date
- Feb 2009
- Location
- New Zealand
- Posts
- 4,547
- Rep Power
- 11
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.
- 10-18-2012, 01:13 AM #6
Member
- Join Date
- Oct 2012
- Location
- Tempe, Arizona
- Posts
- 77
- Blog Entries
- 12
- Rep Power
- 0
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:
You could use the method .toLowerCase() or .toUpperCase() to check both of these without using a logic 'or'.Java Code:if(mainChar == 'A' || mainChar == 'a')
Would do the same thing, and in my opinion is a little simpler.Java Code:if(mainChar.toLowerCase() == 'a')
Where you have:
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:totalDue = 9.95; System.out.println("Total Due: " + totalDue + "$");
Java Code:System.out.println("Total Due: $9.95");
Where you have:
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 && 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");
This makes it a lot easier to look at, and a lot simpler to write.Java Code:if(hoursUsed<0) ..code.. else if(hoursUsed<=10) ..code.. else if(hoursUsed<744) ..code.. else ..code..
After your question is answered about validating what the user inputs, where you have:
Can be switched to just an:Java Code:else if (mainChar == 'C' || mainChar == 'c')
Seeing as it will not be able to get to the if statements unless the user enters an A, B or C.Java Code:else
Now on to your actual question, validating the user input. Where you have:
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): "); packageType = keyboard.nextLine(); char mainChar= packageType.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:System.out.print("Enter package type (A, B, or C): "); char mainChar= keyboard.next().charAt(0);
If the input does not equal A, B OR C.Java Code:else System.out.println("Invalid package type");
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.
- 10-18-2012, 05:02 AM #7
Re: Need help
Please find and go through the Forum Rules -- particularly the third paragraph.
dbWhy do they call it rush hour when nothing moves? - Robin Williams
- 10-18-2012, 10:01 AM #8
Moderator
- Join Date
- Apr 2009
- Posts
- 10,481
- Rep Power
- 16
Re: Need help
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.
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:
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.
- 10-18-2012, 09:42 PM #9
Member
- Join Date
- Oct 2012
- Location
- Tempe, Arizona
- Posts
- 77
- Blog Entries
- 12
- Rep Power
- 0
Re: Need help
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.
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-18-2012, 10:12 PM #10
Moderator
- Join Date
- Feb 2009
- Location
- New Zealand
- Posts
- 4,547
- Rep Power
- 11
Re: Need help
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.(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;
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.)
I agree, and that's why penguin's proposed changes are good ones.(Tolls) But again, that's a legibility thing.
---
@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.
- 10-19-2012, 10:08 AM #11
Moderator
- Join Date
- Apr 2009
- Posts
- 10,481
- Rep Power
- 16
Re: Need help
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.
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:
No.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(); } }
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.Please do not ask for code as refusal often offends.


3Likes
LinkBack URL
About LinkBacks
Reply With Quote

Bookmarks