Please help with this....(thank you)
Hi. I am new to the Dev. Connection and new to Java Programming. In fact what I am posting is a homework assignment that I have put several hours into and I cannot get it to perform properly. I am not looking for someone to do it for me --- rather to give me some pointers on how I can find the error and fix the problem myself. I mean what good would it do me if you (the experienced programmer) solved the whole thing for me? I want to be a kick-ass programmer and I would never be any good if everyone else did my work.
Thanks in advance for any advice.
Program Code:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
public class ReverseString
Method Name: Main()
Return Value: none
Input Parameters: none
Method Description: This is the method that makes it all go!
public static void main( String args[] )
String sentence = ""; //String variable to hold user input
String output = ""; //String variable to enable display of output
String buffer = "";//String variable to hold output
//Display an input dialog
sentence = JOptionPane.showInputDialog(
"Enter the Sentence you want to see in REVERSE:");
//Pass String variable 'sentence' to StringTokenizer object
StringTokenizer st = new StringTokenizer(sentence);
//Array to hold tokens
String tokenHolder[] = new String[st.countTokens()];
//Walk through the tokens
while (st.hasMoreTokens())
for (int i = 0; i < st.countTokens(); i++)
tokenHolder[i] = st.nextToken();
String reversedTokens[] = new String[tokenHolder.length];
//Walk through the array in reverse
for (int j = tokenHolder.length - 1; j >= 0; j--)
//Add the reversed token to the ouptut string
output += tokenHolder[j] + " ";
//Display Output
JOptionPane.showMessageDialog (null, output,
"Reversing the Contents of an Input String.",
JOptionPane.INFORMATION_MESSAGE );
//Exit cleanly
System.exit( 0 );
}//EOMain
}//EOF
The problem is that when I run this application the output does not yield a string that has had the tokens extracted from the user input in reverse. Instead for the input "this is a test" --I get "nullnull is test". Why?
Thanks again.
...but since you are learning, and would like to know where was the bug, I tried your code and updated it.
The only two small problems I found:
1. You have a while loop that checks if there are more tokens.. it's not needed and this while loop will only run because by the second run, you would have consumed all the tokens in the for loop, check would fail and while loop will be exited. [I have removed this while loop in my version below]
2. Now, here is the bug:your for loop has a condition that evaluates (i < st.countTokens()).
Now count tokens will only return "remaining" tokens. Assuming test string "this is a test", countTokens return 4. Then as you consume the first token, it is 3, then 2 then 1. All this while for loop's i is going 1,2...
i = 0, countTokens = 4
i = 1, countTokens = 3
i = 2, countTokens = 2, check fails, and for loop is exited.
So all you have in your array is first two tokens. Rest of the array is null as it was when you created the array.
So then when you loop back and check index 3,2,1,0.. 3 and 2 elements are still nill, that's why you get the result you are getting.
Here is the fixed code:
String sentence = "this is second test"; //String variable to hold user input
String output = ""; //String variable to enable display of output
String buffer = "";//String variable to hold output
st = new StringTokenizer(sentence);
int tokenCount = st.countTokens();
//Array to hold tokens
String tokenHolder[] = new String[tokenCount];
//Walk through the tokens
for (int i = 0; i < tokenCount; i++)
tokenHolder[i] = st.nextToken();
String reversedTokens[] = new String[tokenCount];
//Walk through the array in reverse
for (int j = tokenCount-1; j >= 0; j--)
//Add the reversed token to the ouptut string
output += tokenHolder[j] + " ";
System.out.println(output);
}
Similar Messages
-
HELP WITH THIS, THANK YOU.
1st time on here..... help... with installing, and understanding, thank you, wayne. <phone # removed by mod - kglad> anytime.
Help us to help you:
What OS?
What browser?
And... DON'T post your phone number. This is a public forum and it ISN'T a safe practice to do that. -
I have a picture of the itunes icon and a usb cable on my screen and cant seem to get rid of it as it is frozen with this on. Can any one help please
Connect the iPod to your computer and restore via iTunes
iTunes: Restoring iOS software -
Hello, Honestly I just updated my 4s and my iPad 3 to iOS 6 and when try to press on the Music app or the iTunes app it says "cannot connect to iTunes Store" Could you please help me with this thank you so much, Charbel from Lebanon
See these previous discussions help.
App Store Updates (but only Updates)...: Apple Support Communities
Apps suddenly don't update: Apple Support Communities -
I tried to downgrade my iCloud and when i did it never refunded me can you please help me with this thank you James
<Personal Information Edited by Host>How did you try to downgrade
(Don't post your telephone number in public places, unless you need more useless phone calls) I will ask for it to be removed. -
I have treated photos in final cut using effects. The problem is I can not export them. Please help me. Thank you-
Ernest,
This is how I do it: With all the video & still's in the time line, I click on each (even if I have to use the command key and click on each file). When each file is active I go under SHARE- go to EXPORT MEDIA- I use the Apple Pro Res codec 4:2:2. If you do not click on each file in the time line it will not be exported out.
Hope this helps. -
I lost my iphone 5 yesterday and i tried using find iphone and i found it offline. What is best to do? Please help me. Thank you..
If you forgot (or don't know) your passcode, restore the device from backup on the last computer it was synced with when the passcode was turned on... this will remove the passcode. If you do not have access to the last computer it was synced with, or you don't have a backup, you will have to force it into recovery mode & restore as a new device.
See this for more info... http://support.apple.com/kb/HT1212 -
i have two iphone wich are protected by two different password ! but when i woke up today ! i'v found that my two iphone ( iphone 5 et iphone 4 ) refuse my passwords of 4 numbers i have important data and i dont want to lose please help me ! thank you !
If you forgot (or don't know) your passcode, restore the device from backup on the last computer it was synced with when the passcode was turned on... this will remove the passcode. If you do not have access to the last computer it was synced with, or you don't have a backup, you will have to force it into recovery mode & restore as a new device.
See this for more info... http://support.apple.com/kb/HT1212 -
Hi. I have an iPhone 4s. The music doesn't play when I connect it to my car stereo. It used to play previously but stopped playing all of a sudden. My phone is getting charged when I cut it to the USB port. Please help with this. The iOS is 6.1.3.
Hello Priyanks,
I found an article with steps you can take to troubleshoot issues with an iPhone not connecting to your car stereo:
iOS: Troubleshooting car stereo connections
http://support.apple.com/kb/TS3581
Thank you for using Apple Support Communities.
Best,
Sheila M. -
The map of Republic of Armenia in iOS 6 is not good. Please help us. Thank you in advance. Maps
Hi Naren,
When I double-click on this data type from the ABAP editor, it takes me to the definition screen.I wish I could put screenshots in this message but I don't know how. Anyway, the definition says it is a "table" type. There are four tabs underneath - Attributes, Line Types, Initialization, and Access Key. Under "Line Type," the properties are as follows:
Predefined Type
Data Type: STRING
No. of Characters: 0
Decimal Places: 0
Thank you in advance for your help.
Peter -
i can't connect my iphone to itunes or the activation server cannot be reached , please Help me ! , thank you
I am having this problem too. Anyone pls help!
-
Hi, i bought an hp mini 110 at a pawn shop. but it has a bios password, after 3 attempts a get an error message system halt and CNU9341LSH can you please help me? Thank you!
Bobby.
CLICK ON THIS.
http://h30434.www3.hp.com/t5/Notebook-Operating-Systems-and-Software/Hi-Please-help-unlock-compaq-mi...
REO
HP Expert Tester "Now testing HP Pavilion 15t i3-4030U Win8.1, 6GB RAM and 750GB HDD"
Loaner Program”HP Split 13 x2 13r010dx i3-4012Y Win8.1, 4GB RAM and 500GB Hybrid HDD”
Microsoft Registered Refurbisher
Registered Microsoft Partner
Apple Certified Macintosh Technician Certification in progress. -
HT201303 I forgotten my answer of security questions, please help me. Thank you !
I forgotten my answer of security questions, please help me. Thank you !
You need to ask Apple to reset your security questions; as described in this article, it can be done in Vietnam by phoning 1-201-0288 and then 800-708-5413.
(107433) -
Please help with this Premiere Pro CS5 encoding error
VBR 2 pass encoding getting stuck at 50% in Premire Pro CS5. I assume this is the starting point of pass #2. The Error message states that one of the temporary files created during first pass cannot be read. I confirmed that said file exists, it is in the correct location and has the correct file name. Interestingly, at times, the 2 pass encoding proceeds through completion without issues, but I haven't been able to identify the reason for this. PLEASE HELP!! Thank you.
Thank you so much for replying. I tried running as administrator and it did not correct the issue. Luckily I did figure out the problem after trying various ways. It so happens that Windows seven sets "read Only" attributes to files within folders that you create by right clicking on the drive name and using "New Folder". So, when the encoder tries to over-write on one of the temporary files it created during the first pass it can't do it and it issues the error "Cannot open file for writing...etc.". I fixed it by right clicking inside the folder contents and changing the attribute. Now it works. This is the error that I was getting:
-
Hi, how can I set up icloud for my ipad and iphone5? I missed tout he initial setup step and now want to have both the devices under icloud. Please help...thank you!
Go to Settings>iCloud and sign in with your Apple ID to create the account. Then turn on the data you wish to sync with iCloud. See http://www.apple.com/icloud/setup/ios.html.
-
I tried to download an app on the mac app store and it continues to say: "There was an error in the App Store. Please try again later. (null)" Please help me. Thank you.
Change your Date & Time settings to reflect automatic. It will fix the problem.
Maybe you are looking for
-
Can't create a print queue on OS 10.7 via HP driver installed by Apple
I've ust bought a reconditioned iMac and am getting applications up and running, but I'm unable to get my HP Laserjet 2200DN printer working. The Add Printer pane (Print & Scan Preferences) remains blank: Name & Location and Print Using & Add areas a
-
Re install on XP PRO Windows Media Edition. SR2023WM
My motherboard died. I replaced it with a HP Compaq motherboard with a Dual Core CPU. I thought that I might as well upgrade since I had to get a new motherboard . The first time it was turned on, it booted up, loaded Windows and went to my Desk Top,
-
hi please can anyone help, i have two ipods and only one itunes, is there any way i can have two itunes librarys, as when i use the two ipods they lose everything.
-
How to automate backup in Max DB
Hi All, I am using Maxdb.I would like to know is there any way to automate backup in maxdb(Like scheduling the backup at a perticular time) can any one of you help in this regard.I am using windows o/s and maxdb. Thanks in advance. Thanks Venu
-
Using log4j with JavaFX and Netbeans 6.8
Hello, I'm trying to use log4j within a JavaFX project using NetBeans 6.8. I've donwloaded the .zip file from the Apache website and added the log4j-1.2.16.jar to the project's libraries. Then I added the imports: import org.apache.log4j.Logger; impo