How to clear the console in java program? [duplicate] - java

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.

Related

ArrayList with more than 4680 elements returning blanks [duplicate]

This question already has an answer here:
Java console bug under windows
(1 answer)
Closed 8 years ago.
I'm trying to turn an ArrayList to a String, and then print it. This is my code:
private void toString(ArrayList<Integer> answer) {
String s = "";
for(int i = answer.size() - 1; i >= 0; i--){
s = s+answer.get(i);
}
System.out.println(s);
}
It works fine for smaller ArrayLists, but for some reason, for ArrayLists with more than 4680 elements, it returns a bunch of blank spaces. And it's NOT a problem with the String. I tried printing the characters individually to the screen, and even writing the ArrayList to a text file. Still nothing over 4680. ALSO, even weirder, if I just print the ArrayList directly to the screen, it works fine! I tried increasing the console output. Nothing. Does anybody have any idea what's happening?!?
Try to activate "Word Wrap" in the Eclipse console. It worked me.
RESOLVED.
It was indeed the same bug as in Java console bug under windows. I set the fixed width to 400 in Eclipse and it worked. Thanks Michael Petch!

No Viable Alternative to Input '\\n" Python Error

I am working on a large scale project that involves giving a python script a first name and getting back a result as to what kind of gender it belongs to. My current program is written in Java and using Jython to interact with a Python script called "sex machine." It works great in most cases and I've tested it with smaller groups of users. However, when I attempt to test it with a large group of users the program gets about halfway in and then gives me the following error:
"Exception in thread "main" SyntaxError: No viable alternative to input '\\n'", ('<string>', 1, 22, "result = d.get_gender('Christinewazonek'')\n")
I am more accustomed to Java and have limited knowledge of Python so at the moment I don't know how to solve this problem. I tried to trim the string that I'm giving the get_gender method but that didn't help any. I am not sure what the numbers 1, 22 even mean.
Like I said since I'm using Jython my code would be the following:
static PythonInterpreter interp = new PythonInterpreter();
interp.exec("import sys, os.path");
interp.exec("sys.path.append('/Users/myname/Desktop/')");
interp.exec("import sexmachine.detector as gender");
interp.exec("d = gender.Detector()");
interp.exec("result = d.get_gender('"+WordUtils.capitalize(name).trim()
+"')");
PyObject gendAnswer = interp.get("result");
And this is pretty much the extent of Jython/Python interaction in my Java code. If someone sees something that's wrong or not right I would certainly appreciate if you could help me. As this is a large project it takes time to run the whole program again only to run into the same issue, so because of this I really need to fix this problem.
I don't know if it helps but this is what I did and it works for me.
public static void main(String[] args){
PythonInterpreter pI = new PythonInterpreter();
pI.exec("x = 3");
PyObject result = pI.get("x");
System.out.println(result);
}
Not sure if you sorted this out, but have an extra apostrophe on
d.get_gender('Christinewazonek'')
Just like in Java, everything you open you need to close, and in this case you opened a string containing )\n") which was not closed.
Depending on the interpreter you are using, this can be flagged easily. Perhaps you might try different interpreter.

Race between System.out and System.err in java [duplicate]

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.

difference between System.out.println() and System.err.println()

What is the difference between System.out.println() and System.err.println() in Java?
In Java System.out.println() will print to the standard out of the system you are using. On the other hand, System.err.println() will print to the standard error.
If you are using a simple Java console application, both outputs will be the same (the command line or console) but you can reconfigure the streams so that for example, System.out still prints to the console but System.err writes to a file.
Also, IDEs like Eclipse show System.err in red text and System.out in black text by default.
System.out is "standard output" (stdout) and System.err is "error output" (stderr). Along with System.in (stdin), these are the three standard I/O streams in the Unix model. Most modern programming environments (C, Perl, etc.) support this model.
The standard output stream is used to print output from "normal operations" of the program, while the error stream is for "error messages". These need to be separate -- though in most cases they appear on the same console.
Suppose you have a simple program where you enter a phone number and it prints out the person who has that number. If you enter an invalid number, the program should inform you of that error, but it shouldn't do that as the answer: If you enter "999-ABC-4567" and the program prints an error message "Not a valid number", that doesn't mean there is a person named "Not a valid number" whose number is 999-ABC-4567. So it prints out nothing to the standard output, and the message "Not a valid number" is printed to the error output.
You can set up the execution environment to distinguish between the two streams, for example, make the standard output print to the screen and error output print to a file.
Those commands use different output streams. By default both messages will be printed on console but it's possible for example to redirect one or both of these to a file.
java MyApp 2>errors.txt
This will redirect System.err to errors.txt file.
System.out's main purpose is giving standard output.
System.err's main purpose is giving standard error.
Look at these
http://www.devx.com/tips/Tip/14698
http://wiki.eclipse.org/FAQ_Where_does_System.out_and_System.err_output_go%3F
System.out.println("wassup"); refers to when you have to output a certain result pertaining to the proper input given by the user whereas System.err.println("duh, that's wrong); is a reference to show that the input provided is wrong or there is some other error.
Most of the IDEs show this in red color (System.err.print).
this answer most probably help you it is so much easy
System.err and System.out both are the same both are defined in System class as reference variable of PrintStream class as
public final static PrintStream out = null;
and
public final static PrintStream err = null;
means both are ref. variable of PrintStream class.
normally System.err is used for printing an error messages, which increase the redability for the programmer.
A minor difference comes in both when we are working with Redirection operator.
It's worth noting that an OS has one queue for both System.err and System.out. Consider the following code:
public class PrintQueue {
public static void main(String[] args) {
for(int i = 0; i < 100; i++) {
System.out.println("out");
System.err.println("err");
}
}
}
If you compile and run the program, you will see that the order of outputs in console is mixed up.
An OS will remain right order if you work either with System.out or System.err only. But it can randomly choose what to print next to console, if you use both of these.
Even in this code snippet you can see that the order is mixed up sometimes:
public class PrintQueue {
public static void main(String[] args) {
System.out.println("out");
System.err.println("err");
}
}

How to set a string's color [duplicate]

This question already has answers here:
How to print color in console using System.out.println?
(15 answers)
Closed 3 months ago.
Does anyone know how I would set the color of a string that will be printed using System.out?
This is the code I currently have:
System.out.println("TEXT THAT NEEDS TO BE A DIFFERENT COLOR.");
Console
See the Wikipedia page on ANSI escapes for the full collection of sequences, including the colors.
But for one simple example (Printing in red) in Java (as you tagged this as Java) do:
System.out.println("\u001B31;1mhello world!");
The 3 indicates change color, the first 1 indicates red (green would be 2) and the second 1 indicates do it in "bright" mode.
GUI
However, if you want to print to a GUI the easiest way is to use html:
JEditorPane pane = new new JEditorPane();
pane.setText("<html><font color=\"red\">hello world!</font></html>");
For more details on this sort of thing, see the Swing Tutorial. It is also possible by using styles in a JTextPane. Here is a helpful example of code to do this easily with a JTextPane (added from helpful comment).
JTextArea is a single coloured Text component, as described here. It can only display in one color. You can set the color for the whole JTextArea like this:
JTextArea area = new JTextArea("hello world");
area.setForeground(Color.red)
for linux (bash) following code works for me:
System.out.print("\033[31mERROR \033[0m");
the \033[31m will switch the color to red and \033[0m will switch it back to normal.
Google aparently has a library for this sort of thing:
http://code.google.com/p/jlibs/wiki/AnsiColoring
There's also a Javaworld article on this which solves your problem:
http://www.javaworld.com/javaworld/javaqa/2002-12/02-qa-1220-console.html
setColor(). Assuming you use Graphics g in an AWT context.
Please refer to the documentation for additional information.
If you're printing to stdout, it depends on the terminal you're printing to. You can use ansi escape codes on xterms and other similar terminal emulators.
Here's a bash code snippet that will print all 255 colors supported by xterm, putty and Konsole:
for ((i=0;i<256;i++)); do echo -en "\e[38;5;"$i"m"$i" "; done
You can use these escape codes in any programming language. It's better to rely on a library that will decide which codes to use depending on architecture and the content of the TERM environment variable.
Download jansi-1.4.jar and Set classpath and Try This code 100% working :
import org.fusesource.jansi.AnsiConsole;
import static org.fusesource.jansi.Ansi.*;
import static org.fusesource.jansi.Ansi.Color.*;
public class SampleColour
{
public static void main(String[] args)
{
AnsiConsole.systemInstall();
System.out.println(ansi().fg(RED).a("Hello World").reset());
System.out.println("My Name is Raman");
AnsiConsole.systemUninstall();
}
}
I created an API called JCDP, former JPrinter, which stands for Java Colored Debug Printer. For Linux it uses the ANSI escape codes that WhiteFang mentioned, but abstracts them using words instead of codes which is much more intuitive. For Windows it actually includes the JAnsi library but creates an abstraction layer over it, maintaining the intuitive and simple interface created for Linux.
This library is licensed under the MIT License so feel free to use it.
Have a look at JCDP's github repository.
public class colorString
{
public static void main( String[] args )
{
new colorString();
}
public colorString( )
{
kFrame f = new kFrame();
f.setSize( 400, 400 );
f.setVisible( true );
}
private static class kFrame extends JFrame
{
#Override
public void paint(Graphics g)
{
super.paint( g );
Graphics2D g2d = (Graphics2D)g;
g2d.setColor( new Color(255, 0, 0) );
g2d.drawString("red red red red red", 100, 100 );
}
}
}
A string is traditionally a sequence of characters, either as a literal constant or as some kind of variable. The latter may allow its elements to be mutated and the length changed, or it may be fixed (after creation).
As per your question, it is not clear what actually you want. But you can store color information to a string variable. Are you thinking of setting the color in a string variable?

Categories

Resources