is there any way to print a line in java and then go back to the beginning of that line, i tried using \r however this only prints a new line and does not go back to the original line.
So basically if the user inputs "Hello this is lol"
I want to print all the a's in the sentence (none), all the b's, etc...
eg.)" e "
then"He " --> this however must be on the same line as above and you must be able to see the change.
Is there any way to do this in java?
I ran this on my Mac, which is a FreeBSD underneath:
public static void main (String[] args) {
System.out.println("Hello there\rWho's");
}
It printed out
Who's there
If you are running this on Windows, then I cannot be sure what they'll do, but all *nixes should behave as posted.
This is not really a java question, but has more to do with the behavior of your terminal/console.
You are sending the correct character to return to the beginning of the line '\r' but it sounds like your console is not handling this correctly.
You should also be using the print() and not println() function (or whatever the methods are called on the specific object you are using to write). The println() function will add a '\n' character which will cause a new line to appear.
It depends what you mean by "print a line". If you're talking about the command line of an OS window, then you're going to nee to about output terminal control characters to control the cursor.
It depends very much on which operating system you are using, but there are libraries output that can make it simpler.
You might be able to output the backspace character \b to erase the current line, but it may not work.
Related
I want some code in my program to run only if the user has input the character '*' at the command-line as a command-line argument. This is the code I've used:-
//myfile.java
import java.io.*;
public class myfile {
public static void main(String[] args) {
if(args[0].equals("*")){
//do stuff
System.out.println(args[0]);//added this line to see what exactly was being passed
}
}
}
When this program is executed at the command-line by entering:-
java myfile *
the output I'm expecting to see on the screen is the asterisk character, instead the output displayed is 'myfile.class'. Where am I going wrong? Why does Java change the asterisk to the .class file?
Also, note that the program worked perfectly the first four times I executed it and then started doing this!
Thanks in advance for your help.
Where am I going wrong?
The star character needs to be quoted or escaped. Run your java program like this:
java myfile "*"
or
java myfile \*
Why does Java change the asterisk to the .class file?
It doesn't. It is your shell that is doing it. It is shell file expansion ... or "globbing" as it is also called.
Run "ls *" or "echo *" and you will see that the same thing happens.
The command terminal already replaces the asterisk and java already gets the value that you see. I'd use any other character, that has no special meaning to the command terminal or otherwise you must escape the asterisk in your command.
Actually escaping arguments on Windows and especially in cmd.exe is non-trivial. This nice article explains it in detail: Everyone quotes command line arguments the wrong way :
the takaway for your case is: surround the asterisk with quotes.
Answer to your question in the comment:
Using the escape character worked! But I still don't get why it worked without the escape character the first few times
I am not sure, but maybe you run into this behavior: It makes a difference if the pattern can be expanded or not. For example, when I pass Test* as argument, then there are 2 cases to consider:
in the current folder there is a file called Test1.txt: then your java program will get Test1.txt as argument
when there are no matching files, your program will get Test* as argument
However, I am not sure, how this would apply to your case, since you only pass *: that should only work in an empty directory.
System.out.print("I have a question, can you assist me?");
System.out.println();
System.out.println("How can I make a gap between these two statements?");
I tried to use println(), thinking that it would create a blank line, but it didn't.
Try:
public class Main {
public static void main(String args[]) {
System.out.println("I have a question, can you assist me?\n");
System.out.println("How can I make a gap between these two statements?");
}
}
P.S. \n is newline separator and works ok at least on Windows machine. To achieve truly crossplatform separator, use one of methods below:
System.out.print("Hello" + System.lineSeparator()); // (for Java 1.7 and 1.8)
System.out.print("Hello" + System.getProperty("line.separator")); // (Java 1.6 and below)
Here's what's going on.
System.out.print("I have a question, can you assist me?");
You have now printed a bunch of characters, all on the same line. As you have used print and have not explicitly printed a newline character, the next character printed will also go onto this same line.
System.out.println();
This prints a newline character ('\n'), which is not the same as printing a blank line. Rather, it will cause the next character printed to go onto the line following the current one.
System.out.println("How can I make a gap between these two statements?");
Since you just printed a newline character, this text will go onto the line directly following your "I have a question" line. Also, since you have called println, if you print anything right after this, it will go onto a new line instead of the same one.
To put a blank line between the two statements, you can do this (I know, I know, not entirely cross-platform, but this is just a very simple example):
System.out.println("I have a question, can you assist me?");
System.out.println();
System.out.println("How can I make a gap between these two statements?");
Since you are now printing two newline characters between the two lines, you'll achieve the gap that you wanted.
Beware that adding a bare "\n" to the string you are outputting is liable to make your code platform specific. For console output, this is probably OK, but if the file is read by another (platform native) application then you can get strange errors.
Here are some recommend approaches ... that should work on all platforms:
Just use println consistently:
System.out.println("I have a question, can you assist me?");
System.out.println();
System.out.println("How can I make a gap?");
Note: println uses the platform default end-of-line sequence.
Use String.format:
String msg = "I have a question, can you assist me?%n%nHow can " +
"I make a gap?%n";
System.out.print(String.format(msg));
Note: %n means the platform default end-of-line sequence.
Note: there is a convenience printf method in the PrintWriter interface that does the same thing as String.format
Manually insert the appropriate end-of-line sequence into the string; see the end of #userlond's answer for examples.
Use:
system.out.println("\n");
\n takes you to new line.
You can use the below code. By that method you can use as much line gap as you want. Just increase or decrease the number of "\n".
System.out.print("Hello \n\n\n\n");
System.out.print("World");
If you want to leave a single line space in java,you could use
System.out.println("");
But if you want to leave Multiple line spaces in java,you could use
System.out.println("/n/n/n/n");
which means that each '/n' represents a single line
What about this one?
public class Main {
public static void main(String args[]) {
System.out.println("Something...");
System.out.printf("%n"); // Not "\n"
System.out.println("Something else...");
}
}
"%n" should be crossplatform-friendly.
I'm writing a program that (at one point) makes a command-line call to another native application, gets the output from that application, and puts it into a JTextPane as a String. The problem is, it doesn't seem to grab the newline characters the way it should. Because I'm using linux, each line ends with a ^M instead of a \n.
Is there any way to tell Java to look for those and create a newline in the string?
private void getSettings() {
Commander cmd = new Commander();
settings = cmd.getCommandOutput("hdhomerun_config " + ipAddress + " get /sys/boot");
settingsTextPane.setText(settings);
}
I end up with the output barfed into one line and wrapped around in the text pane.
As I recall Unix displays ^M for the carriage return character \r so you could try to replace it by using the replace method of the String class
settingsTextPane.setText(settings.replace('\r', '\n'));
Thanks guys, I looked through my code again and realized I was reading the output from the program one line at a time, and just appending the lines. I needed to add a \n at the end of each line that I read. Correct me if I'm wrong, but I believe Java automatically corrects newlines based on your operating system.
this is my first post. I am excited to a part of this community and I have been struggling with this problem for a while, so here goes:
In the following code:
if (j == 0)
{
if (!Arrays.equals(cipherData, c))
{
System.out.print("C: ");
for (int i = 0; i < encryptedData.length; i++)
System.out.print((char)cipherData[i]);
System.out.println();
}
}
The System.out.println()
method returns nothing at all. No line, or anything and I have no idea why. The goal is to print a blank line after printing the byte array is printed above when those if conditions are true.
Any help would be much appreciated and welcome.
System.out.print() does not print a newline character.
You're outputting a bunch of stuff, then printing a newline with System.out.println(). This causes the cursor to drop to the next line.
You need another one if you want a blank line after that.
Edit to add: I missed the fact that your for loop conditional is ... different than the array you're printing. Did you mean for that to be the case?
Also, since you're possibly printing non-printable characters, it is completely plausible that you're causing the terminal to be in a state where the newline will no longer work.
What it comes down to is, println() isn't broken. Either it's not getting called, or if you don't see a newline occur when it is called then the terminal is in a state where it no longer recognizes it.
Check
http://docs.oracle.com/javase/6/docs/api/java/io/PrintStream.html#println()
You may need System.out.print('\n');
Before iterating for loop you can check length of encryptedData
System.out.println("encryptedData.length:: "+ encryptedData.length);
if encryptedData.length return greater than 1 then it will go into for loop.
You should debug step by step .
I have concerns about this:
System.out.print((char)cipherData[i]);
Assuming that cipherData is an array of bytes, then casting a byte to a char and printing it via a character stream is not likely to give pretty results. For a start, bytes that are less that 32 decimal will map to ASCII "control characters".
And also you may be printing the wrong array ... or using the length of the wrong array.
(But the explanation for your problem is that you need to call println a second time to be a blank line. The first println is just terminating the line containing the ... umm ... "characters" from your cipher array.)
Sounds like the problem is that you have run a JVM without any standard output attached. Like on Windows, using javaw.exe to run a jar (which is the default, beware). Java.exe outputs to the console window, if you run it from a console, but javaw.exe does not. If you run the program from the file explorer window, even though you are using java.exe, you still won't get any standard out, because it's hidden by windows.
So, run the program in a command line window, and use java.exe, not javaw.exe.
I think this is a standard problem which may have been asked before but I could not get the exact answer so posting the issue.
The issue is that our server is running on a linux box. We access the server over the browser on a window box to enter data into field which is supposed to contain multiple lines which user can enter by pressing the enter key after each line
Abc
Def
GHI
When this input field (this is a text area),is read on the linux machine, we want to split the data based on new line character.
I had three question on this.
Does the incoming data contain "\r\n" or "\n"
If incoming data does contain "\r\n", the linux line.separator property (vm property) would not work for me as it would say "\n" and therefore may leave "\r" in the data.
If "\r" is left in the data, if I open the file on a windows machine, will this mean a newline character?
Finally can anyone tell me the standard way to deal with this issue?
The standard java.io.DataInputStream and java.io.BufferedInputReader both handle this automatically through the readLine() method. You really should not use DataInputStream for this since it does not support character sets correctly and it's readLine() has been deprecated for a long time.
For text output, you can use java.io.PrintWriter in which it's printLn(), and related methods with parameters, output the correct newline sequence for the current platform. java.io.BufferedWriter also handles this correctly and provides a public newLine() method.
Linux uses \n.
Windows uses \r\n.
Therefore, unless you've tweaked something in linux, it should be coming in \n.
You could regex out \r\n and \n and replace with whatever you want to avoid problem 3.
http://en.wikipedia.org/wiki/Newline
Rather than using regular expression, you can also make it simpler by doing something like.
StringBuilder sb=new StringBuilder();
// append your texts here and to go to a new line use
if(System.getProperty("os.name").startsWith("Windows")){
sb.insert("\r\n");
}
else {
sb.insert("\n");
}
So if your local environment is windows , you can have this working locally and will also work if you're deploying to a different linux based environments.
Probably try this?
String[] lines = inputString.split("\r?\n");
Not 100% sure about the syntax but the basic idea of the regex is: "zero or one \r, and exactly one \n". Or, if you just want to normalize the input:
inputString = inputString.replace("\r?\n", "\n");
Doesn't seem very painful to me. ;-)
Thanks for the response guys.. Finally looking at suggestion given by Kevin, we used StringReader and BufferedReader wrapper over it to overcome the issue. We used string reader as data is read as a string from the request.
Hopefully this question helps people in future