Given a string value, how can I display it on the screen in my console? What do I have to write to make that happen?
As an example, this is the code I have so far:
public class Main {
public static void main(String[] args) {
String message = "I am a school student and just started learning Java.";
// What to write next?
}
}
It works, but it obviously does not display the value on the console yet. What do I have to write to show it?
I want it to look something like this:
But all I get is this:
By default, a Java program doesn't print anything. You need to explicitly tell your program to print output. Here are some of the ways that you can do that:
To print a String to standard output:
System.out.print(message);
To print a String followed by a (platform appropriate) line separator:
System.out.println(message);
To print a String to the standard error stream:
System.err.print(message);
To print to the console (e.g. if standard output could have been redirected to a file):
Console console = System.console();
if (console != null) { // Note that in some contexts there
// is not a usable `Console`...
console.writer().print(message);
}
Note that the above print and println methods are defined by the PrintWriter class. There are convenience overloads for all of the primitive types, and also for Object. In the latter case, what is printed is the result of calling toString() on the argument.
There are also printf methods for formatting a number of arguments according to a format string.
For more information, read the following:
The javadocs for java.lang.System, java.io.PrintWriter and java.io.Console.
Oracle Java Tutorials: The Hello World Application.
System.out.print(message);
// or
System.out.println(message); // creates a new line after print is done.
There are many great courses on YouTube or the web for free which cover all basics and also intermediate topics.
Surf the internet about a problem before asking here. I'm not telling you that you can't ask here but you should put some effort into researching before asking.
Related
This question already has answers here:
JUnit test for System.out.println()
(14 answers)
Closed 4 years ago.
I try to write JUnit tests in IntelliJ for an application, that modifies a String. Now how can I test one particular print on the console?
Let's assume the start-string is stored in args[0] as "Hello World" and we have a method that can change a single letter in the string. The string will be printed out after the execution of the method.
public class modifyString {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while(true) {
// Print the string
System.out.println(args[0]);
// Wait for a userinput that only contains two chars,
// e.g. '0h' <- 'Change the index 0 to 'h''
// (the order of the chars is unimportant)
String input = scanner.nextLine();
if(preconditionFullfilled(input)) {
executeOperation(input, args);
}
}
}
}
For example: The expected output for the input '0h' with a 'Hello World' string in args[0] should be 'hello World'.
How do I write a JUnit test to test this particular result?
As far as I know there is no way to test the already printed output if you use System.out. for printing. I think it could be theoretically possible if you use another PrintStream class, but I would highly recommend you to change your Code in a way that you work with Strings or StringBuilders as return types and do the printing separately. So you can easily write Unit tests for all your methods.
In addition if you want to test the written output you could write the output in e.g a .txt file and them comparing the content with a expected result file. However this goes into integration tests and would be basically overkill here.
I hope this help you a bit.
If you have further questions please ask.
Regards,
Kai
The standard JVM method for reading a password from the command line without showing it is java.io.Console.readPassword(). This, however, shows nothing while the user is typing; users accustomed to graphical programs will expect symbols such as "•" or "*" to appear in place of the characters they type. Naturally, they will also want backspacing, inserting, and so on to work as normal, just with all the characters being operated on replaced with the same symbol.
In 2019, is there a generally accepted JVM procedure for showing "*******" when the user types "hunter2" in a console application? Can this even be done properly without a GUI? A 2011 SO question on the topic got an answer linking to this article on the topic; can we do better nowadays than the rather elaborate solution shown therein?
(I happen to be using Kotlin as my language of choice, so a Kotlin-specific solution will satisfy if there is one.)
hunter2? Wow. Reference acknowledged.
There is no easy way. The primary problem is that the standard System.in doesn't give you any characters at all until the user has pressed enter, so there's no way to emulate it (if you try to read char-for-char from System.in and emit a * every time a key is pressed, that won't work).
The lanterna library at https://github.com/mabe02/lanterna can do it, though. If you want to emulate it, it's.. very complicated. It has branching code paths for unix and windows. For example, on unix, it uses some hackery to figure out what tty you're on, and then opens the right /dev/tty device. With lanterna, writing this yourself would be trivial.
It's that or accept Console.readPassword()'s blank nothingness, really. Or, write a web interface or a swing/awt/javafx GUI.
I think answer to your question can be found here in stackoverflow itself.
please see this:
masking-password-input-from-the-console-java
sample code from there:
import java.io.Console;
public class Main {
public void passwordExample() {
Console console = System.console();
if (console == null) {
System.out.println("Couldn't get Console instance");
System.exit(0);
}
console.printf("Testing password%n");
char passwordArray[] = console.readPassword("Enter your secret password: ");
console.printf("Password entered was: %s%n", new String(passwordArray));
}
public static void main(String[] args) {
new Main().passwordExample();
}
}
hope this is helpful. :)
Is there a way to dynamically change output in Java? For instance, in a terminal window if I have:
System.out.print("H")
and then I have:
System.out.print("I")
The output will be:
HI
Is there a way to assign a position to outputs that allows you to replace characters dynamically? For instance (and I know this would not output what I want, I merely want to demonstrate my thinking) this:
System.out.print("H")
Thread.sleep("1")
System.out.print("I")
And it would first print out
H
and then after a second, replace the H with an I?
I'm sure this sounds stupid, I am just interested in dynamically changing content without GUIs. Can someone point me in the direction for this technique? Thank you very much in advance.
You might want to take a look at
System.out.printf
Look at the example shown here: http://masterex.github.com/archive/2011/10/23/java-cli-progress-bar.html
edit:
printf displays formatted strings, which means you can adapt that format and change it for your needs.
for example you could do something like:
String[] planets = {"Mars", "Earth", "Jupiter"};
String format = "\r%s says Hello";
for(String planet : planets) {
System.out.printf(format, planet);
try {
Thread.sleep(1000);
}catch(Exception e) {
//... oh dear
}
}
Using the formatted string syntax found here: http://docs.oracle.com/javase/6/docs/api/java/util/Formatter.html#syntax
As the comment says this solution is only limited to a singular line however dependent on your needs this might be enough.
If you require a solution for the whole screen then a possible solution would be (although quite dirty) would be to hook the operating system using JNA and get a handle on the console window, find its height and then loop println() to "clear" the window then redraw your output.
If you would like to read more then I can answer more questions or here is a link: https://github.com/twall/jna
You can use \b to backspace and erase the previous character.
$ cat T.java
import java.lang.Thread;
public class T {
public static void main(String... args) throws Exception {
System.out.print("H");
System.out.flush();
Thread.sleep(1000);
System.out.print("\bI\n");
System.out.flush();
}
}
$ javac T.java && java T
I
It will output H, then replace it with I after one second.
Sadly, it doesn't work in Eclipse console, but in normal console it does.
This is what you need (uses carriage return '\r' to overwrite the previous output):
System.out.print("H");
Thread.sleep(1000);
System.out.print("\rI");
The C library that is usually used to do this sort of thing is called curses. (Also used from scripting languages that rely on bindings to C libraries, like Python.) You can use a Java binding to it, like JCurses. Google also tells me a pure-Java equivalent is available, called lanterna.
In java when we take input from console we get a String, even if we want an integer as input we get a input in String format, then we covert it in integer format using several methods, like Integer.parseInt(). Where as C/C++ also take input from console but there we get integer values directly from console we does not require methods to convert them. Then why does java follows such long procedure. **What is the reason behind such an architecture of Java ?
//In java we follow the following process
public static void main(String args[])
{int i = Integer.parseInt( args[0]);// here we get input in String format and then convert it
}
//In C++ we follow the following :
void main()
{int i;
cin>>i;
}
Both C/C++ and Java takes input form Console then why java takes it in String Format and C++ does not ??
Check out java.util.Scanner, it might do what you need:
http://download.oracle.com/javase/6/docs/api/java/util/Scanner.html
Java - If you use the Scanner class you can get the input in the required data type. It's not only String java accepts.
If you take an integer from the console in C, it will require you to atoi() the input.
You always get a string when reading from stdin. In C++ however, the >> operator overload used when writing to an int performs the conversion - so it's just a different way of converting but in both languages it's necessary.
You are right that it's nicer in C++ though since you can use pretty much the same code no matter what data type you have.
This has been asked before, but was not clarified to the point where I get it. Similar to the one or two other threads I've seen on this subject, I'm working on a chat client with command line inputs for logging in/off, disconnecting, etc. and I am unsure how to simulate this in a JUnit test case. Other responses indicated that I should try changing the System.in to a separate InputStream but...then what?
tl;dr: I have a method in my actual code for parsing command line input, and need a JUnit way of testing that these were entered and appropriately processed.
EDIT: It seems I misunderstood the question. I usually use the term "command line input" to refer to command line arguments given to the process to start with, rather than interactive console input. However...
Handing your real code either a different InputStream or possibly even a Reader or Scanner would indeed help - anything to separate the "getting input" part from the console. You can then fake the input all in one go pretty easily, using a String as input in your test code, and then either converting it to bytes and wrapping those bytes in a ByteArrayInputStream or wrapping the string directly in StringReader.
The downside of this is that there's no easy way of making this "pause" after one command in order to check the results.
You may want to alter the design somewhat so that the part which reads the input is separated from the part which handles the input. The reading part could be a very simple loop, on the order of:
String line;
while ((line = reader.readLine()) != null) {
handleInput(line);
}
You could then potentially leave that part untested by unit tests, or write some relatively primitive tests - but you can then test handleInput extensively, as it's now separated from the input source.
Original answer
If you've extracted the parsing code from the code which really starts the application, it's easy: run that code, and check the results. This will be easiest if you have some sort of class encapsulating the options, of course. For example, your main method might look like this:
public static void main(String[] args) {
Options options = Options.parse(args);
// Use options here
}
Then you can just test Options.parse very easily.