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!""");
Related
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.
So I have to get words from a text file, change them, and put them into a new text file.
The problem I'm having is, lets say the first line of the file is
hello my name is bob
the modified result should be:
ellohay myay amenay isay bobay
but instead, the result ends up being
ellomynameisbobhay
so scanner has .nextLine() but I want to have a method that is .nextWord() or something, so that it will recognize something as a word until it has a space after it. how can I create this?
nextLine() gives you the whole line.
What you should use is just next(), that will give you the next word.
Also see String.split() or StringTokenizer if you wanted to post-process whole lines. It sound s as though in your situation just using the scanner is fine, but I though i'd mention it because I assumed you'd have just used those methods if you knew about them.
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.
I have a switch statement acting as a menu, in this I am trying to read the users input. Currently I am using variable=in.next(); and this works. However it will only read one word and at points the user may need to enter more, so I tried using variable=in.nextLine();, which compiles, but when I run the program, I select my choice from the menu, and it skips the reading in and return to the menu.
Any help would be appreciated, thanks :)
Just use:
name=in.nextLine();
and
String choice = in.nextLine();
This should be in the constructor, and at the top of runApp.
That way, you're not leaving the new line in the buffer (where it will be used for e.g. dp).
You should have:
dp=in.nextLine();
as described in your question.
You either have to strip the newline character \n from the user input or assume it's there in your switch statement.
Pretty much because you decided to use nextLine() the user input to the computer will look like this
f\n
So just compare the strings accordingly!
OK I think I am too inept at Java and have put my question badly.
When I take the users input it takes only 1 word, I want it to take everything they put basically, and when I use nextLine, this just skips the reading and takes me back to selecting a choice.
Switch selector can be only integer, short, char or enum. String cannot be used as a switch selector.
If I understood you correctly you would like to control your flow using words entered by user. If you have predefined list of words I'd suggest you to use enum:
enum Words {
start, stop, beep,
}
Now user enters a word beep. You can say:
Words command = Words.valueOf();
///
switch (command) {
case start: /* start something */ break;
case stop: /* stop something */ break;
case beep: /* beep!!! */ break;
default: throw new IllegalArgumentException("Unknown command " + command);
}
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.