wood burning stoves 2.0*
The moose likes Beginning Java and the fly likes Trouble with getting input from keyboard Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Trouble with getting input from keyboard" Watch "Trouble with getting input from keyboard" New topic
Author

Trouble with getting input from keyboard

Shannon Pitts
Greenhorn

Joined: Dec 30, 2011
Posts: 13
Hi, I literally just started programming tonight, and I've hit a bit of a snag. I'm writing a little to-do list type program, and right now I'm just running it on the command line because GUIs are for later. I've got this so far:

I tested all the cases before I started adding bells and whistles to the "new" option. Everything worked fine, program exited prettily and all was well. I added in the actual statements for the "new" command and now when I run it, I'll get all the way down to displaying "Task added! What's next?" when the program seems to run through the loop twice and spit out "Improper command. Please try again." (from the default case) twice. I can continue typing as normal and the rest of the commands work at that point, but I can't seem to figure out why I'm getting this bizarre behavior.

I'm using Eclipse IDE and I haven't quite figured out how to get it to show me my variables while the program is running, and I imagine that would help immensely. If anyone can tell me what I'm doing wrong here, I'd really appreciate it.
Praveen Kumar M K
Ranch Hand

Joined: Jul 03, 2011
Posts: 256
Welcome to the ranch!

What was the input that you gave after you saw "Task added! What's next?"? (am referring to line 36 and am assuming it was after this input that you got the erroneous display of "Improper command...")


I tested all the cases before I started adding bells and whistles to the "new" option


Is the highlighted part an idiom? What does it mean
Praveen Kumar M K
Ranch Hand

Joined: Jul 03, 2011
Posts: 256
One more thing, I see that you are using a string as an input to the switch case - are you on Java 7? If so, I can only take guesses from here on in as I haven't worked on it.

In Eclipse, you have an option called Debug As --> Java Application. Double click on the blue margin to add break points and then run the program in the debug mode as said in the previous sentence. Once the program "takes a break" at the break point Eclipse automatically changes the display into a Debug "perspective". You will see a window called "Variables" which will have current state of all variables alive at that point.




You can read about debugging here - Eclipse Debugging
Shannon Pitts
Greenhorn

Joined: Dec 30, 2011
Posts: 13
After I enter in the description of the task I'm creating, I press enter and receive back "Task Added! What next?" then "Improper Command" twice in rapid succession without me pressing any more buttons, that's what makes it really strange.

And yes, "bells and whistles" is an idiom; it basically means that I'm adding fancier things to my (currently) simple program.

Thanks for the information about Eclipse! I'll mess with it a bit and see if I can get some more answers.

ETA: Yeah, I'm using Java 7. I can't imagine how else I'd be able to use the keyboard input to determine what the program does next. I guess it used to be kind of complicated?

Edit Again:

<del>Okay, upon further testing, if I use a command as the name of the task, I don't get the "Improper Command" response, so my theory is that even though the input is used inside the new case, it's also being checked against all the other cases, but the output isn't being put out until that case breaks and we go back to the beginning of the loop. I'm going to try changing names of variables to see if that fixes things.</del>

Turns out it's only grabbing the first word, not the whole sentence if you type more than one for the description! Then it's going back and using the other words as commands!
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 38007
    
  22
Bells and Whistles. Yes, it is an idiom.
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 38007
    
  22
Add a line like this to display the input: System.out.printf("Input = \u201c%s\u201d%n", input); where you are calling the String in question input. You will get “” around the output.
Shannon Pitts
Greenhorn

Joined: Dec 30, 2011
Posts: 13
Campbell Ritchie wrote:Add a line like this to display the input: System.out.printf("Input = \u201c%s\u201d%n", input); where you are calling the String in question input. You will get “” around the output.


Thanks, but I also figured out I can just use Scanner.nextLine() instead of Scanner.next() and it will go until the user hits enter.
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 38007
    
  22
Beware of nextLine(); it doesn’t do what most people think it does.
Shannon Pitts
Greenhorn

Joined: Dec 30, 2011
Posts: 13
Yeah, I noticed that. If I just changed the one line I needed to nextLine(), it did what you're describing, but by changing them all to nextLine() I haven't had any troubles with it.

Now I just need to learn how to deal with files!
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 38007
    
  22
I haven’t got a link to it on this computer, but Google for Java Tutorials file input output and you should find something useful This is one of the hits from that Google search.
Praveen Kumar M K
Ranch Hand

Joined: Jul 03, 2011
Posts: 256
Shannon Pitts wrote:
ETA: Yeah, I'm using Java 7. I can't imagine how else I'd be able to use the keyboard input to determine what the program does next. I guess it used to be kind of complicated?


Well, in the previous versions of Java the switch case was only taking in integer inputs, so you would have to think in the lines of Case 1 and Case 2 instead of Case "new" and Case "edit"...Keyboard input is still okay, but you would've had to key in numbers instead of string commands.
Shannon Pitts
Greenhorn

Joined: Dec 30, 2011
Posts: 13
Campbell Ritchie wrote:I haven’t got a link to it on this computer, but Google for Java Tutorials file input output and you should find something useful This is one of the hits from that Google search.


Thanks! I'm actually looking at that right now, though I'm running into the age-old problem of them telling me WHAT I can do, but not WHY. All I know is I want to check for a file, open it if it's there and create objects based on the lines in it, or create the file if it's not there, then when I'm finished with everything, write the new information back to the file and close it. I don't know whether I need a BufferedOutputStream or what have you. I've been writing down words I don't recognize so I can look them up, but it's slow going.
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 38007
    
  22
You appear to have two independent problems: One is how to read text from a file, which is best done with a FileReader and a BufferedInputStream, which you will have read about in the tutorial.
The other is how to create an object from the data in your file; that depends on the format of the file and all its information being in the correct order and the correct positions.
Shannon Pitts
Greenhorn

Joined: Dec 30, 2011
Posts: 13
Campbell Ritchie wrote:You appear to have two independent problems: One is how to read text from a file, which is best done with a FileReader and a BufferedInputStream, which you will have read about in the tutorial.
The other is how to create an object from the data in your file; that depends on the format of the file and all its information being in the correct order and the correct positions.


You are correct, but I also want to be able to write any changes the program makes back out to the file again, which is where I think the output stream would come in.
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 38007
    
  22
Beware reading and writing the same file simultaneously. You may find the OS locks the file, so you can read or write, but not both simultaneously.
If you do write simultaneously, you may find you delete the information you want to read, or (if you have append activated), you append everything you read, so your file grows forever until it occupies all the available memory
Yes, you would use a FileWriter and BufferedOutputStream.
You know you can so use Scanner and Formatter, but like Writer and Reader, they are only any good for text files. I am not sure whether you can use Writers and Readers for non-text files, but I think Scanner and Formatter are strictly for text use.

You might be better off creating a new file for the output, and renaming it. If you want it to have the same name as the input file, you might have to delete that first.
Another suggestion. If your file isn’t too large you can keep all the Strings read in memory in a List<String> or similar. Don’t try to put more than a few million lines into your List, depending on how much memory you have got.
Shannon Pitts
Greenhorn

Joined: Dec 30, 2011
Posts: 13
Maybe there's a better way to do this.. let me describe what I'm trying to do, and perhaps you'll know an easier way to accomplish what I'd like.

When the program is started, it looks for a file called tasklist.txt. If it finds the file, it reads the information in the file line by line, and assigns the information it finds into task objects, one for each line (I haven't worked out how to do that yet, but I'm sure it's possible). Then the user does whatever they want to do in the program, be it creating, editing or deleting task objects, as well as displaying the current list (created by iterating through the array that holds the task objects, not the text file). Then when the user finishes, the last thing the program does before quitting will be to write the task objects in the array back to the text file, one line per object.

Is it possible to open the file, read out the contents and save them into objects, then close the file, then when the program closes, reopen the file to write, write the data, then close both file and program? The only problem I can see is that if the program closes unexpectedly you'll lose any changes to the list since the last save, but I can't think of any other way for the program to have the data persist, besides databases which I'm not quite ready for yet.
Paul Clapham
Bartender

Joined: Oct 14, 2005
Posts: 18541
    
    8

Shannon Pitts wrote:Is it possible to open the file, read out the contents and save them into objects, then close the file, then when the program closes, reopen the file to write, write the data, then close both file and program? The only problem I can see is that if the program closes unexpectedly you'll lose any changes to the list since the last save, but I can't think of any other way for the program to have the data persist, besides databases which I'm not quite ready for yet.


Absolutely. Lots of programs work that way -- for example, text editors, which I'm sure you are familiar with.

It's true that if your program crashes then the changes in progress are lost. That's one of the features of that program design. But I wouldn't worry about that just yet. Start by getting a working program first, and add complex but inessential features later.
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 38007
    
  22
That sounds quite like what I was thinking of earlier. The problem with an array is that you have to set its size in advance, before you know how many lines there are in the file. It may be easier with a List, which is easy enough to use.Don’t forget to import java.util.List and java.util.ArrayList.

Once you get that far, you can display all the text on screen. Now you know the reading is working all right.

You want to do these things in small stages. Now create a dummy Task class, like this, which does nothing, but allows you to test the writing back to file. You can now convert your List to a List<Task> and rather than adding the line, you add new Task(textLine)Note I have overridden the three commonly-used Object class method, implemented comparable so it would sort in ASCIIbetical order of the commands, and made the class immutable. You can change all those features later.

Now you can get a List<Task>, and iterate that List, and write all the Task objects to a new text file. Now you can inspect that file, and verify it has been written correctly. The 263b bit will require you use a text editor which supports Unicode.
Once you have got the output file written correctly, you can consider replacing the input file.
Last of all, replace the Task class with something which does something real
Shannon Pitts
Greenhorn

Joined: Dec 30, 2011
Posts: 13
Okay! I got the file reading and writing working. I can create tasks and have them save to the file when I close the program. Victory!

I've run into another snag. I'm trying to build the delete functionality right now, and everything works, except I can't figure out how to prevent it from throwing an exception if the user enters a number that isn't on the list. (IE, they choose 4 when the highest number on the list is 3). Supposedly ArrayList.remove() returns true if the item is found and successfully deleted, but I can't figure out how to capture that and use it in a while statement so that if it returns false, the user is told to pick a different number. I thought about just checking to see if the object exists before attempting to delete, but I've found that it's very difficult to reference an object in an ArrayList the way you would an array. I can't just type taskList[N] because it insists on having taskList<Task> but if I stick [N] on the end of that, it gives me an error. I'm not sure how I'm supposed to reference these objects.
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 38007
    
  22
Well done

You can check whether the index is in the List by checking that i > 0 and i < myList.size(). If it is in that range, all well and god, otherwise you want to print error messages and take no further action.
By the way remove(int) doesn’t return a boolean, but an E. Have another look at the two versions of remove().
Beware of using boxing to remove something from a List<Integer> (which I don’t think you have), because it will go for the index, not the element.
Shannon Pitts
Greenhorn

Joined: Dec 30, 2011
Posts: 13
That was just the thing I needed! Thank you. I feel like parts of my code may be a bit redundant, but I can go back and clean it up after I finish making it work.
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 38007
    
  22
You’re welcome

All beginners write redundant code; when I used to have coding modules I could delete line after line of somebody else’s code without it having the slightest effect on its functionality
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Trouble with getting input from keyboard
 
Similar Threads
Having troubles with a complex program, need help with an illegal start of type error.
Can't add to ArrayList within switch statement?
Taking input with Scanner : need to exit on pressing enter key
Needs help in editing
need help with endless loop when dealing with "if (keyboard.hasNextDouble())"