How to make a space between a line in Java? - java

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.

Related

Java or Eclipse 'fails' on Whitespaces(?)

After many questions asked by other users this is my first one for which I was not able to find a fitting answer.
However, the problem sounds weird and actually is:
I have had more than one situation in which whitespaces were part of the problem and common solutions to be find on stackoverflow or elsewhere did not help me.
First I wanted to split a String on whitespaces. Should be something like
String[] str = input.split(" ")
But neither (" ") nor any regex like ("\\s+") worked for me. Not really a problem at all. I just chose a different character to split on. :)
Now I'm trying to clean up a string by removing all whitespaces. Common solution to find is
String str = input.replaceAll(" ", "")
I tried to use the regex again and also (" *", "") to prevent exception if the string inludes no whitespaces. Again, none of these worked for me.
Now I'm asking myself whether this is a kinda weird problem on my Java/Eclipse plattform or if I'm doing something basically wrong. Technically I do not think so, because all code above works fine with any other character to split/clean on.
Hope to have made myself understood.
Regards Drebin
edit to make it clearer:
I'm caring just about the "replacing" right now.
My code does accept a combination of values and names separated by comma and series of these separated by semicolon, e.g.:
1,abc;2,def;3,ghi
this gets two time splitted, first on comma, then on semicolon. Works fine.
Now I want to clear such an input by removing all whitespaces to proceed as explained above. Therefore I use, as already explained, String.replaceAll(" ", ""), but it does NOT work. Instead, everything in the string after the FIRST whitespace, no matter where it is, gets removed and is lost. E.g. the String from above would change to
1,abc;
if there is whitespace after the first semicolon.
Hope this part of code works for you:
import java.util.*;
public class Main {
public static void main(String[] args) {
// some info output
Scanner scan = new Scanner(System.in);
String input;
System.out.println("\n wait for input ...");
input = scan.next();
if(input.equals("info"))
{
// special case for information
}
else if(input.equals("end"))
{
scan.close();
System.exit(0);
}
else
{
// here is the problem:
String input2 = input.replaceAll(" ", "");
System.out.println("DEBUG: "+input2);
// further code for cleared Strings
}
}
}
I really do not know how to make it even clearer now ...
The next method of Scanner returns the next token - with the default delimiters that will be a single word, not the complete line.
Use the nextLine method if you want to get the complete line.

How to make multiple lines after System.out.println in the cmd?

import java.util.Scanner;
public class ChristmasSong{
public static void main (String[] args)
Scanner scanner = new Scanner(System.in);
System.out.println("What would like to do? (Do one action) (Do another action) Exit");
This is the beginning of my program. Using Java, how do I make the expression inside the System.out.println appear in mulitple lines on the cmd when I execute the program?
Like I want to make it say
What would you like me to do?
(Do one action)
(do another action)
exit
instead of
What would you like me to do? (Do one action) (Do another action) Exit
and I want the user to type in their option and make the program act according to the option. This is more of format and style kind of question. It probably sounds stupid, but I'm a beginner. Just a week of experience in class and I want to get better. If you could help me out. That would be awesome. Thanks.
System.out.println() outputs line breaks using the platform's preferred line separator
\n The newline (line feed) character ('\u000A')
System.out.println("What would you like me to do?");
System.out.println("(Do one action)");
System.out.println("(do another action)")
System.out.println("exit");
alternatively
System.out.println("What would you like me to do?\n(Do one action)\n(do another action)\nexit");
The second version outputs newline characters, which is likely to be inappropriate on Windows or Mac OS.
For more info regarding performance have a look System.out.println() vs \n in Java
In Java 15, a new feature called Text Blocks are available while in Java 13 and Java 14, these are preview features.
Text blocks help to achieve the results more elegantly and are readable than the accepted answer.
Text blocks starts with three double-quote marks """
Inside the text blocks, we can freely use newlines and quotes without the need for escaping line breaks.
Example:
String text = """
Players take turns marking a square.
Only squares not already marked can be picked.
Once a player has marked three squares in a row, he or she wins!
If all squares are marked and no three squares are the same, a tied game is declared.
Have Fun!""");

Java, end of line with system.out.print

I have done some research concerning System.out.print() and System.out.println() and I discovered that System.out.println() add the end of line at the end of printed line.
System.out.println("Test");
Output only :
Test
but does not print end of the line.
System.out.print("Test");
Output only:
Test
but does not end the line and leave some place for other words or numbers, etc etc.
A more illustrative way is:
Test_____________________________________________ (All "blank" spots)
Is there a way to, force an end of line with System.out.print() directly after the word Test? Will the usage of % will remove the "blank" spots?
Or a way to code a function that will end the line after I used several System.out.print() to print a sentence?
For exemple :
System.out.print("Test);
System.out.print("Test);
will outpost a pure:
Test Test
like System.out.println("Test Test")
You can append line separator, Note that it is platform dependant, so :
Windows ("\r\n")
Unix/Linux/OSX ("\n")
pre-OSX Mac ("\r")
If you want to get line separator depending on actual system you can just use :
System.getProperty("line.separator"); for pre Java 7
System.lineSeparator(); for Java 7
Then you just append your separator to your string in System.out.print, like :
System.out.print("Word\n");
You can do System.out.print("Test\n").
System.out.println("Test"); will print end of the line. When you don't see it in your IDE it doesn't mean it isn't here. Try:
System.out.println("Test1");
System.out.println("Test2");
System.out.println("Test3");
which will produce:
Test1
Test2
Test3
From the docu of the println(String):
Prints a String and then terminate the line. This method behaves as though it invokes print(String) and then println()
and from the docu of the println():
Terminates the current line by writing the line separator string. The line separator string is defined by the system property line.separator, and is not necessarily a single newline character ('\n').
For getting an OS independent EOL character you could try
System.getProperty("line.separator");
and then appending that to your string ?
Why do you want to manually do that though since there is a function to do it for you ?
You can explicitly include a newline char in what you are printing:
System.out.print("Test\n");
This will force the newline while using the print function.
You can force a manual newline like so:
System.out.print("Test\n");
You can also mix the two when you need to print then end the line like so:
System.out.print("This is on ");
System.out.print("the same line.");
System.out.println(" and now we'll end the line");
System.out.println("This is on a different line.");

Carriage return Java

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.

Scanner cuts off my String after about 2400 characters

I've got some very basic code like
while (scan.hasNextLine())
{
String temp = scan.nextLine();
System.out.println(temp);
}
where scan is a Scanner over a file.
However, on one particular line, which is about 6k chars long, temp cuts out after something like 2470 characters. There's nothing special about when it cuts out; it's in the middle of the word "Australia." If I delete characters from the line, the place where it cuts out changes; e.g. if I delete characters 0-100 in the file then Scanner will get what was previously 100-2570.
I've used Scanner for larger strings before. Any idea what could be going wrong?
At a guess, you may have a rogue character at the cut-off point: look at the file in a hex editor instead of just a text editor. Perhaps there's an embedded null character, or possibly \r in the middle of the string? It seems unlikely to me that Scanner.nextLine() would just chop it arbitrarily.
As another thought, are you 100% sure that it's not all there? Perhaps System.out.println is chopping the string - again due to some "odd" character embedded in it? What happens if you print temp.length()?
EDIT: I'd misinterpreted the bit about what happens if you cut out some characters. Sorry about that. A few other things to check:
If you read the lines with BufferedReader.readLine() instead of Scanner, does it get everything?
Are you specifying the right encoding? I can't see why this would show up in this particular way, but it's something to think about...
If you replace all the characters in the line with "A" (in the file) does that change anything?
If you add an extra line before this line (or remove a line before it) does that change anything?
Failing all of this, I'd just debug into Scanner.nextLine() - one of the nice things about Java is that you can debug into the standard libraries.

Categories