I have a java program that simulates values and returns them. But I want to see how far the simulation is by printing the current state.
Ex:
System.out.print("Number of simulations: ");
for(int i=0;i<NUMBER_OF_SIMULATIONS;i++){
/* Do my calcutions*/
System.out.print("\b" + i);
}
I thougth this was possible, but the output is:
Number of simulations: 0?1?2?3?4?5?6?7?8?9?10?11?12?
I only want to see the current state, so not a counter.
So if i++ current i removes and i+1 will shown.
\b will go back 1 char. As Pawel Veselov said, use \r to go to the beginning of the line.
Another important thing is that, depending on where you're testing the output (IDE), it won't work as expected. You should test in a shell (Windows cmd or Linux terminal) in order to see the real result.
If you where expecting to edit the value to have one line being:
Number of simulations: 0 //and then editing just the number to have
Number of simulations: 1
Its not possible on the command line to my knowledge.. every time you call System.out.print you are writing/adding the value into the "out" stream, hence the count being added every time is called at the end of the line with print().
You would need to add a new line for every time you print it.
System.out.println("Number of Simulations: " + i);
And that will give you a new line everytime.
Edit: Its not what you want, but thats a cleaner way to visualize it and how programs normally log steps.
Related
So, before I start I just wanted to say that I'm very new to Java as a language and I've been reading a text book that was recommended to me.
One of the examples provided within the text book on for loops had the following code, which is meant to generate an infinite for loop until the user presses the character 'S' on their keyboard.
Here is the code:
class ForTest {
public static void main(String args[])
throws java.io.IOException {
int i;
System.out.println("Press S to stop.");
for (i = 0; (char) System.in.read() != 'S'; i++)
System.out.println("Pass #" + i);
}
}
I copied the code exactly as it was written within the book but when I run the program, to my surprise, it doesn't start printing out numbers onto the console. Additionally, whenever I press any keys on the keyboard it generates three numbers within the sequence. Example shown below:
I have also included a screenshot of the code from the book below:
I was wondering whether anyone knows why this is the case!
Any help would be greatly appreciated thanks.
The reason it's printing multiple times is because multiple characters are detected.
In your case, it's printing twice because you entered a value (Pass 1) and a new line (Pass 2)
The problem you have is not with System.in.read(), but because the console is usually using a buffered approach. Meaning that data is only transferred to the System.in.read() once you press enter.
So to get the example working, you would have to switch the console to an unbuffered mode, but there is no portable way to do this, because there are so much different types of consoles. Maybe have a look at what editor/console the book is using
This block of code looks like it was written by someone who was deliberately trying to make it obtuse and difficult to comprehend for a beginner.
The middle expression of a for statement is the criterion for taking the next step of the loop. It is evaluated before each step of the loop to determine whether the for loop is complete yet. In this case, it calls in.read() and checks if the input is S before each step of the loop.
in.read() waits for the next line of input it gets. When you enter a value and press Enter, that line gets read, so the loop takes a step. And a new line is also entered, so the loop takes a second step.
It will not print lines to the console unless you enter lines, because in.read() causes the program to block (wait) for the next input.
I posted here a few weeks ago regarding a project I have for work. The project began as creating a simple little program that would take an incoming ACH file and read each line. The program would also ask a user for a "reason code" and "bank" which would affect the next step. The program would then reformat all the data in a certain way and save it to an external file. For those that don't know, an ACH is simply a text based file that is in a very concrete format. (Every character and space has a meaning.)
I have completed that task using a few GUI items (Jcombobox, JFileChooser, etc), string array lists, buffered reader/writer, and lots of if/else statements.
The task has now been expanded to a much more complicated and I don't know exactly how to begin, so I thought I would seek the communities advice.
When an ACH file comes in it will be in a format that looks something like this:
101 100000000000000000000000000000
522 00000202020382737327372732737237
6272288381237237123712837912738792178
6272392390123018230912830918203810
627232183712636283761231726382168
822233473498327497384798234724273487398
522 83398402830943240924332849832094
62723921380921380921382183092183
6273949384028309432083094820938409832
82283409384083209482094392830404829304
900000000000000000000000000000000
9999999999999999999999999999999999999
9999999999999999999999999999999999999
(I will refer to each line by " " number, for example "1 number" are the lines that begin with 1)
The end result is that the lines of data are maniuplated and put into "batches". The output file begins with the "1 number"
and then contains a batch with the format of
5
6
8
5
6
8
5
6
8
We continue using the same "5 number" until all sixes that were below it in the original file have been written, then we go to the next "5" and work with the "6" below it.
So, my project now is to create a full GUI. After the user inputs the file the GUI will have some type of drop down box or similar list of all the "6" numbers. For each number there should be another drop down box to choose the reason code (there are 7 reason codes).
Basically the ultimate objective is:
Display all the "6" numbers and give the user the ability to choose a reason code for each.
Allow the user to only select a certain amount of the "6" numbers if they wish.
Is it possible for me to do this using Buffered Reader/ Writer? I currently save the values into Array Lists using the following code:
while((sCurrentLine = br.readLine()) !=null)//<---------This loop will continue while there are still lines to be read.
{
if (sCurrentLine.startsWith("5")){//<------------------If the line starts with "5"..
listFive.add(sCurrentLine);//<-------------------------Add the line to the array list "listFive".
countFive++;//<---------------------------------------------Increase the counter "countFive" by one.
}else if (sCurrentLine.startsWith("6") && countFive==1){//<---------If the line starts with "6" and countFive is at a value of 1..
listSix.add(sCurrentLine);//<---------------------------------------Add the line to the array list "listSix".
}else if (sCurrentLine.startsWith("6") && countFive==2){//<-----------------If the line starts with "6" and countFive is at a value of 2..
listSixBatchTwo.add(sCurrentLine);//<--------------------------------------Add the line to the array list "listSixBatchTwo".
}else if (sCurrentLine.startsWith("6") && countFive==3){//<-----------------------If the line starts with "6" and countFive is at a value of 3..
listSixBatchThree.add(sCurrentLine);//<------------------------------------------Add the line to array list "listSixBatchThree".
}else if (sCurrentLine.startsWith("6") && countFive==4){//<------------------------------If the line starts with "6" and countFive is at a value of 4..
listSixBatchFour.add(sCurrentLine); //<--------------------------------------------------Add the line to array list "listSixBatchFour".
}else if (sCurrentLine.startsWith("8")){//<-----------------------------------------------------If the line starts with "8"..
listEight.add(sCurrentLine);//<----------------------------------------------------------------Add the line to array list "listEight".
}else if (sCurrentLine.startsWith("1")){//<-----------------------------------------------------------If the line starts with "1"..
one = sCurrentLine;//<-------------------------------------------------------------------------------Save the line to String "one".
}else if (sCurrentLine.startsWith("9") && count9 == 1){//<---------------------------------------------------If the line starts with "9" and count9 is at a value of 1..
nine = sCurrentLine;//<-------------------------------------------------------------------------------------Save the line to String "nine".
count9 = 0;//<--------------------------------------------------------------------------------------------------Set count9 to a value of 0.
}else if (sCurrentLine.startsWith("999") && count9 == 0){//<-----------------------------------------------------------If the line starts with "999" and count9 is at a value of 0..
listNine.add(sCurrentLine);//<---------------------------------------------------------------------------------------Add the line to array list "listNine".
}else{
}
}
If anyone can point me where I can get started I would be very grateful. If you need more information please let me know.
Update:
Here is an example of my JOptionPane with decision making.
String[] choices = {"Wells Fargo", "Bank of America", "CitiBank", "Wells Fargo Legacy", "JPMC"};
String input = (String) JOptionPane.showInputDialog(null, "Bank Selection", "Please choose a bank: ", JOptionPane.QUESTION_MESSAGE, null, choices, choices[0]);
if (input.equals("Wells Fargo"))
{
bank = "WELLS FARGO";
}else if (input.equals("Bank of America")){
bank = "BANK OF AMERICA";
}else if (input.equals("CitiBank")){
bank = "CITI BANK";
}else if (input.equals("Wells Fargo Legacy")){
bank = "WELLS FARGO LEGACY";
}else if (input.equals("JPMC")){
bank = "JPMC";
}
}else{
}
Let's assume I wanted to use the Buffered Writer to save all of the "6" numbers into a String array, then put them into a drop down box in the GUI. How could I accomplish this?
Can you use the input from Buffered Writer in a GUI..
Well, a BufferedWriter is not used to get input but rather to output information, but assuming that you meant a BufferedReader, then the answer is yes, definitely. Understand that a GUI and getting data with a BufferedReader are orthogonal concepts -- they both can work just fine independently of the other. The main issues involving reading in data with a Bufferedhaving a GUI
Say a JOptionPane for example.
I'm not sure what you mean here or how this relates.
If yes, then how could I go about doing that? In all the examples I have seen and tutorials about JOptionPane everything is done BEFORE the main method. What if I need if statements included in my JOptionPane input? How can I accomplish this?
I'm not sure what you mean by "everything is done before the main method", but it sounds like you may be getting ahead of yourself. Before worrying about nuts and bolts and specific location of code, think about what classes/objects your program will have, and how they'll interact -- i.e., what methods they will have.
I believe I just had an idea of how I need to proceed first. Can someone please verify? 1. Create static variables representing the lines that will be read. (Such as a static ArrayList.
No, don't think about static anything off the bat, since once you do that, you leave the OOP realm and go into procedural programming. The main data should be held in instance variables within a class or two.
Create the actual GUI, outside the main Method.
I'm not sure what you mean "outside the main method", but the GUI will consist of multiple classes, probably one main one, and an instance of the main class is not infrequently created in the main method, or in a method called by the main method, but queued onto the Swing event thread.
Create the Buffered Reader which will write to the variables mentioned in #1, inside the main method.
Again, I wouldn't do this. The main method should be short, very short, and its reason for existence is only to start your key objects and set them running, and that's it. Nothing critical (other than just what I stated) should be done in them. You're thinking small toy programs, and that's not what you're writing. The reader should be an instance variable inside of its own class. It might be started indirectly by the GUI via a control class which is a class that responds to GUI events. If you need the data prior to creation of the GUI, then you will have your main method create the class that reads in the data, ask it to get the data, and then create your GUI class, passing the data into it.
I have a text file containing some lines of text, separated by commas like this:
"Every strike brings me closer to the next home run. –Babe Ruth",
"It is hard to fail but it is worse never to have tried to succeed.-Theodore Roosevelt",
"People often say that motivation doesn’t last. Well, neither does bathing – that’s why we recommend it daily. - ZigZiglar"
Now my aim is to read from this file, pick a random line, and print it in the console. New lines may also be added by the user. Now, what are the methods i should use to read from the file and without storing each line in a Array of string(then picking a random line would be easy, but will cost memory), how can i pick a random line, from the text?
If you don't want to keep these sentences in memory, then you have to know at each moment of time the count of all lines in the file - say N. Then do this: generate a random number k such that 1 <= k <= N, open your file, and read line by line until you reach line k. Now read line k and return it to the user. So the answer is: you have to read your file sequentially.
So I have been wondering how to do this for some time, and I thought who better to ask then the SO community.
I apologize in advance if this is a little vague, but I will do my best to get my question across.
We all remember the first time we got caught in a infinite loop with a print statement. The terminal fills up fast, and soon all you see it a bunch of scrolling text...
How do I make it not scroll? What I mean is ... How do I overwrite the line that has already been written.
How can I make my infinite loop with a one line print statement(no more than one new line) only print on one line. Where the terminal does not scroll.
Instead of ....
This is an infinite loop
This is an infinite loop
This is an infinite loop
You just have one line that updates every iteration of the loop.
This is an infinite loop
Thanks for reading, comment if this made absolutely no since. I'll try to clarify in a cloudy world...
PS - What I am doing right now is in C, but it wouldn't hurt to know how to do this in other languages.
Question (0.1)
What if you wanted to update multiple lines in place?
printf("This is some text\n");
printf("This is more text\n");
That would give me two lines and I want to update both of them, but not scroll.
You only need carriage return, not line feed hence you need to use only "\r"
Carriage return means bringing the cursor back to the beginning of the line.
Line feed means feeding a new line to the terminal.
In c :
while(1)
{
printf("\r This is an infinite loop.");
}
Since the printf is buffered, therefore it's a good practice to explicitly flush the output stream.
You may use the carriage return escape sequence, or \r. This will return the cursor to the start of the line.
while (1)
{
std::cout << "\rTest.";
}
Try this...
while(1)
{
printf("this id infinite loop\n");
sleep(1);
system("clear");
}
I'm running a simple java program. I programmed it in Netbeans. Everything worked great. Attempted to transition code to use Ant because that's what my class requires, and I'm getting a weird error.
All text coming in from the .txt is in the format,
Baker William Chavez 04/01/05
Sanchez Jose Chavez 06/15/05
etc ...
There about 20 entries, 3 names and a date. Each entry is on its own line.
I'm using this code to read it in.
while ((line = br.readLine()) != null) {
//formatting data correctly
String [] info = line.split(" ");
for(int i = 0; i < info.length; i++){
System.out.println(info[i]);
}
System.out.println(info[0]);
System.out.println(info[1]); /* this line of code */
}
So every info [] is of length 4. When I run the for loop, it prints out everything exactly as expected. Printing out "info[0]" works exactly has expected.
But for some reason when I attempt to print out "info[1]", I get an
java.lang.ArrayIndexOutOfBoundsException: 1
error. I have no explanation for why this happens. When I don't attempt to print out info[1] by itself, my program works correctly. In the for loop, info[1] gets printed out, because the for loop loops through 4 times. This code worked perfectly in Netbeans, but using Ant is doesn't work.
Does anyone know adding or removing just one line,
System.out.println(info[1]);
causes my program to run or throw an exception?
I'm running Ant 1.9.2
I'm running Java 1.7.0_17
I've checked this multiple times, so I'm pretty sure its not something I've made an erro ron. I'm a fairly experienced programmer, so I pretty confident it's not my error. It runs well in Netbeans. I don't have an explanation for the error.
edit 1.
My code throws an error the second time threw the while loop.
Printing out the info[] length, or the line itself works great with I don't print out line[1] by itself. It stills fails and throws an error when I printout the info[1] by itself.
http://pastebin.com/NAUeDsZH
Edit 2.
#Millie Smith was on the right trail because my .txt file wasn't correctly formatted. Viewing it in notepad for some reason didn't display the extra space in between each line.
http://pastebin.com/njjdSHHZ
My correct pastebin.
I was attempting to use code to strip out all of the blank space, commas, new lines, and such,
line = line.replaceAll("\\s+", " ");
line = line.replaceAll(",","");
line = line.replaceAll("\\n", "");
line = line.replaceAll("\\r", "");
String [] info = line.split(" ");
I incorrectly assumed that that code would take care of any irregularities. I was wrong. So on my first pastebin, I formatted the code to what I thought I was dealing with, which was also incorrect.
So if I test for line.length() > 1, that gives me my results that I am looking for. I'm not an experienced programmer as I think I am.
Your last line of the file is BLANK ( probably just a end of line marker ) and this is causing the last .split(" ") to assign a single element array with nothing in it but an empty string in the first position.
Make sure your file doesn't have a ZERO length line as the last line or any of the lines.
Learn to use the step debugger, it is your best friend, and step through the code and see what line is equal to on the very last iteration.
Ant and Netbeans have nothing to do with this error, it is completely data related and we can't see your entire data file in its native format