This question already has answers here:
System.out.println and System.err.println out of order
(7 answers)
Closed 9 years ago.
Please consider this java code:
public class CMain {
public static void main(String[] args){
for (int i = 0; i < 10; i++) {
System.out.println("A");
System.err.println("B");
}
}
}
By a quick look at the code, some of us may think the output has to be the print of As and Bs alternatively. However is not! It is a random appearance of 10 A characters and 10 B ones. Something like this:
Why is that? and what is the solution for it so that the As and Bs gets displayed alternatively ( A B A B A B ...)
Before I ask this question, I checked several other similar questions for solution and non worked for my case! I have brought some of them here:
Synchronization and System.out.println
Java: synchronizing standard out and standard error
Java: System.out.println and System.err.println out of order
PS. I am using Eclipse as my IDE
Why does this happen?
This is because out and err are two different output streams. However, both of them print on console. So you do not see them as different streams. Moreover, when you do out.println(), it is not guaranteed that you will see the output on the console as soon as the statement gets executed. Instead, the strings are usually(depends on the system) stored in an output buffer (if you will) which is processed later by the system to put the output from the buffer onto the screen.
Solution :(
Although, as Eng.Fouad pointed out that you can use setOut(System.err) or setErr(System.out) to make them ordered, I would still not suggest doing that when you are actually putting this in an application (only use it for debugging purposes).
What the proposed solution does is that it will end up using only one stream for both the standard output and the standard error, which I do not think is a good thing to do.
They are different OutputStreams. If you really need to guarantee the order of printing them, use:
System.setErr(System.out);
or
System.setOut(System.err);
Since there are two separate streams, the output you are giving is possible.
Related
I'm writing an application in Java that uses the following external library: SCPSolver (link: http://scpsolver.org/).
The library appears to be a wrapper for a c library and prints some information on the standard out. My problem is I'd like my application to have a clean output: I'm looking for a way to either
a. clear the console, which might be either a system (windows) console or eclipse's console; or
b. straight up prevent the library from printing on the output.
Regarding point a:
I've tried both using
Runtime.getRuntime().exec("cls");
and
System.out.print("\033[H\033[2J");
and neither work.
I've tried printing "\b" characters but to no avail. In all these cases, I get gibberish in the output.
Regarding point b:
I've tried redirecting System.out to a new PrintStream, but it doesn't work. That's most likely because the library is a wrapper to a c library, and the c library prints bypass java's System.out. Thus I'm not really sure this approach would work, as I have no control over what the library does. I've looked in the documentation for a way to disable the output, and haven't found anything useful yet.
A possibly useful note:
Calling
System.out.close();
before asking the solver to solve an LP problem prevents the output from being displayed. Of course, the problem then is: I have no more stream to stdout to print to. Maybe a solution could be getting another stream to the same console? Though I have no idea how to do this.
In short:
The call to lpw.solve() is what prints the undesired output:
LPWizard lpw = new LPWizard();
// ...
LPSolution solution = lpw.solve();
Current output is:
GLPK Simplex Optimizer, v4.65 4 rows, 4 columns, 8 non-zeros
0: obj = 0.000000000e+000 inf = 2.700e+001 (4)
3: obj = 1.350000000e+001 inf = 0.000e+000 (0) OPTIMAL LP SOLUTION FOUND x1: 4.0 x2: 2.5 x3: 7.0 x4: 0.0
I'd expect it to instead be none.
This question already has answers here:
How to clear the console?
(14 answers)
Closed 3 years ago.
import java.util.*;
import java.io.*;
class TreeSetPro
{
public static void main(String $[] )throws IOException
{
TreeSet<String> alpha=new TreeSet<String>();
alpha.add("apple");
alpha.add("Apple");
alpha.add("Ab");
alpha.add("applet");
System.out.println(alpha);
String osname = System.getProperty("os.name");
if (osname.contains("Windows"))
{
Runtime.getRuntime().exec("cls"); //java.io.IOException: Cannot
run program "cls"
}
else
{
Runtime.getRuntime().exec("clear"); //java.io.IOException:
Cannot run program "clear"
}
}
}
I went through nearly all of the post related to clearing the console in java but none of them worked for me. I am using windows 8.1.
How am I supposed to clear the console??
Having tried multiple IDE's, the console isn't meant to be 'cleared' according to Java, whereas in C# or C++ yes you can clear the console because of the way that C# applications are implemented (see all the cmd stuff we sometimes go thru). And since Java is a high-level language, there is really no need for clearing the console from logs, etc...
It is a line by line output, thus for administrative purpose it cannot be cleared.
An alternative method to this is printing out bunch of blank spaces which gives an impression that it is cleared. Even commands like cls/clear puts enough blank spaces.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
Given a string I #eat# #hamburgers# and a StringBuilder eat: [eat, consume, like] hamburgers: [hamburgers, spinach, bananas], I want to randomly replace the words within hashmarks with randomly chosen ones from their wordbanks, so that phrases such as I like bananas and I consume spinach will be generated. Code to randomly select another word, given a token (i.e. eat, hamburgers) has been written.
I need to use this regex #[^#]+# to find words within the initial string contained by hashmarks, pass them to the replace method, and then put their random correlates back inside the initial string. I tried using StringTokenizer, but realized it's not the tool for the job.
I need to somehow extract the first word within hashmarks and pass it to the method calling for its replacement before calling the method archetypeString(#[^#]+#, replacement) in such a way so that when the loop runs again, both the word grabber&passer-to method and the replacement method are then working with the second hashed word.
tokenizer dead-end:
StringTokenizer stt = new StringTokenizer(archetype);
while(stt.hasMoreTokens()){
String temp = stt.nextToken();
if(temp.charAt(0)=='#');
}
and the getPhrase method:
public List<String> getPhrases(StringBuilder fileContent, String token) {
StreamTokenizer tokenizer = new StreamTokenizer(new StringReader(fileContent.toString()));
List<String> list = new ArrayList<String>();
try {
while (tokenizer.nextToken() != StreamTokenizer.TT_EOF) {
if (tokenizer.sval.equals(token)) {
tokenizer.nextToken(); // '['
do {
tokenizer.nextToken(); // go to the number
list.add(String.valueOf(tokenizer.sval));
} while (tokenizer.nextToken() == ',');
break;
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return list;
}
I need to use this regex #[^#]+# to find words within the initial string contained by hashmarks, pass them to the replace method, and then put their random correlates back inside the initial string. I tried using StringTokenizer, but realized it's not the tool for the job.
It is not clear from your question whether this is part of some sadistic homework assignment or just the first way you thought of to solve whatever problem you're trying to solve. This is not a regular expression problem any more than it's a StringTokenizer problem.
Look at String.format(), and the formatting capabilities of Formatter. I do not understand why you would ever need to know what the last string you generated was if your object is to generate the next one at random. Just pick a new random value and format it with String.format().
--
After reading your comment to this answer and looking at the question you referred to, I'm going to make a couple of recommendations.
(1) start with a simpler coding assignment or two, something without regular expressions. Make sure you absolutely understand the following concepts: instance variables. variable scope. public methods versus private methods. passing parameters to methods, and returning values from methods. You can do quite a bit with just that much. You don't need to study inheritance until you have all of those down cold, and I recommend that you do not try.
(2) for each coding assignment for at least your first 5, make sure you have written out what your program is to be provided as data and what output it is supposed to produce. List any constraints someone has given you separately (must use class X, must display error message, whatever).
(3) Put opening braces and closing braces on lines by themselves; match each opening brace with a closing brace indented the same amount. Indent code within each pair of braces another 2 or 3 spaces further to the right. This means that brace pairs inside other brace pairs will be indented further. I know this is not the way you see most code, and plenty of people will tell you that it is "wrong". But until you get comfortable with scope and whether a given place in your code is inside or outside a method or a loop, I think it best that you give yourself these extra visual cues. For someone not familiar with other ways of doing things, this is easiest.
(4) be careful of your terms when posting here. In the other question you refer to, you say it is about inheritance, but it uses "implements", indicating that it is implementing an interface, not inheriting from a class. It is confusing to those of us trying to help you if you get the terminology wrong.
(5) when you post here: post the entire program (these early assignments should all be under 100 lines total, no reason not to post all of it). Make sure it is properly indented; use spaces instead of tabs. In text, and maybe also in comments, point out the place in the code where you seem to have the problem (if you know). If there is an error message, post the entire error message (don't tell us what it is, and don't try to interpret it for us). Work on your code until you have a specific question: why do I get a compile error here? Why do I get (or fail to get) this output? The program outputs X but I expected Y, why is that? etc.
We're not a tutorial shop; most of us need instruction to learn to program, and you need to get most of that somewhere besides here. We are willing to help with your questions, given that your questions are specific and reasonable and you aren't expecting us to provide the instruction. By itself, "I'm lost and need help" is a bit beyond StackOverflow's normal way of operating.
Some classmates and I are working on a homework assignment for Java that requires we print an ArrayList of Strings to a PrintWriter using word wrap, so that none of the output passes 80 characters. We've extensively Googled this and can't find any Java API based way to do this.
I know it's generally "wrong" to ask a homework question on SO, but we're just looking for recommendations of the best way to do this, or if we missed something in the API. This isn't the major part of the homework, just a small output requirement.
Ideally, I'd like to be able to wordwrap the ArrayList's toString since it's nicely formatted already.
Well, this is a first for me, it's the first time one of my students has posted a question about one of the projects I've assigned them. The way it was phrased, that he was looking for an algorithm, and the answers you've all shared are just fine with me. However, this is a typical case of trying to make things too complicated. A part of the spec that was not mentioned was that the 80 characters limit was not a hard limit. I said that each line of the output file had to be roughly 80 characters long. It was OK to go over 80 a little. In my version of the solution, I just had a running count and did a modulus of the count to add the line end. I varied the value of the modulus until the output file looked right. This resulted in lines with small numbers being really short so I used a different modulus when the numbers were small. This wasn't a big part of the project and it's interesting that this got so much attention.
Our solution was to create a temporary string and append elements one by one, followed by a comma. Before adding an element, check if adding it will make the string longer than 80 characters and choose whether to print it and reset or just append.
This still has the issue with the extra trailing comma, but that's been dealt with so many times we'll be fine. I was looking to avoid this because it was originally more complicated in my head than it really is.
I think that better solution is to create your own WrapTextWriter that wraps any other writer and overrides method public void write(String str, int off, int len) throws IOException. Here it should run in loop and perform logic of wrapping.
This logic is not as simple as str.substring(80). If you are dealing with real text and wish to wrap it correctly (i.e. do not cut words, do not move comas or dots to the next line etc) you have to implement some logic. it is probably not too complicated but probably language dependent. For example in English there is not space between word and colon while in French they put space between them.
So, I performed 5 second googling and found the following discussion that can help you.
private static final int MAX_CHARACTERS = 80;
public static void main(String[] args)
throws FileNotFoundException
{
List<String> strings = new ArrayList<String>();
int size = 0;
PrintWriter writer = new PrintWriter(System.out, true); // Just as example
for (String str : strings)
{
size += str.length();
if (size > MAX_CHARACTERS)
{
writer.print(System.getProperty("line.separator") + str);
size = 0;
}
else
writer.print(str);
}
}
You can simply write a function, like "void printWordWrap(List<String> strings)", with that algorithm inside. I think, it`s a good way to solve your problem. :)
On my computer programming class in college, we were asked to create a Java program to read and store various elements on a list.
Storing is not a problem, but I'm having some issues regarding the reading of the values. I'm using "variable = input.nextLine();" (if the variable is String), and the problem is that when I read several values in a row, sometimes the program will just skip past the reading one of them. My teacher recommended me to use input.nextLine() to fix that, but it's not working perfectly, and it seems like a workaround to me. I believe the problem is buffer-related. Is there something similar to C's fflush or fpurge functions on Java?
With a few exceptions, the input I/O classes don't have a flush method equivalent and shouldn't need one. The output I/O classes do have flush methods. You can see this at the JDK 6 Javadoc index for F and scrolling down the the collection of flush() methods.
Are you sure that you're not accidentally reading input.nextLine(); twice in a row and thus discarding one line?
We need to know more information before we can help solve your problem.
NOTE: Please edit your question to add additional information. Look for a small "edit" "button" below your question.
If you are reading from a file, you could use a BufferedReader:
BufferedReader reader = new BufferedReader(new FileReader("somelines_oh_yeah.txt"));
String line;
while((line = reader.readLine()) != null){
//do something.
}
You can use System.out.flush()