Results 1 to 4 of 4
- 04-19-2011, 02:05 AM #1
Member
- Join Date
- Apr 2011
- Posts
- 10
- Rep Power
- 0
Please show an example of a String in a while loop.
Would someone show me an example of a string in a while loop please? I have no idea how so I can't show you what I really meant but this is what I actually wanted to do.
Basically what I wanted was while a user input (which is a name) is not equal to a string. So if someone enter a integer or a number, it prints out "Please enter a name. If the user enter a string, the program continues. I'm terribly sorry if I did not really explain well.
Thank You.
- 04-19-2011, 02:19 AM #2
Sure, no problems
Java Code:int count = 0; while(count < 5) { System.out.println("hello"); count++; }Ahhh! more details.Basically what I wanted was while a user input (which is a name) is not equal to a string. So if someone enter a integer or a number, it prints out "Please enter a name. If the user enter a string, the program continues. I'm terribly sorry if I did not really explain well.
Thank You.
That is a general idea of what to do. Now all you need to do is flesh it out.Java Code:declare boolean while boolean is true { get user input if input is invalid { boolean is false } }
- 04-19-2011, 02:20 AM #3
- Join Date
- Jan 2011
- Location
- Richmond, Virginia
- Posts
- 3,069
- Blog Entries
- 3
- Rep Power
- 7
When you get user input it's always a string.
The best way to approach this would be to get some input and try to parse it.
The parse int method will throw the exception when it tries parsing something that isn't a string representation of an integer, if this happens you know that a non integer was entered and you can break out of the loop. You can repeat this process in the loop until the exception is caught and thrown.Java Code:get input try{ Integer.parseInt(input) } catch(NumberFormatException nfe){ //continue with the program } otherwise ask for input again
There may be other approaches, but they may take more logic.
You can create a method called
which loops through each character and tests if they are letters. Check the character API to see if there is a good method for this.Java Code:public static boolean isWord(String s)
- 04-19-2011, 10:21 AM #4
Member
- Join Date
- Apr 2011
- Posts
- 10
- Rep Power
- 0
Similar Threads
-
String in While loop
By nebulared in forum New To JavaReplies: 4Last Post: 02-20-2011, 04:19 PM -
string loop
By durdanto in forum New To JavaReplies: 4Last Post: 02-18-2011, 09:06 AM -
String and while loop
By Exception in forum Java AppletsReplies: 5Last Post: 09-24-2009, 12:32 PM -
String array for Choice, JOptionPane doesn't show
By themburu in forum Java AppletsReplies: 5Last Post: 05-29-2008, 01:10 PM -
netbeans 6.0 not show commpunent or show blank page
By fahimaamir in forum NetBeansReplies: 1Last Post: 01-26-2008, 06:20 AM


LinkBack URL
About LinkBacks
Reply With Quote

Bookmarks