This question already has answers here:
How to delete stuff printed to console by System.out.println()?
(15 answers)
Closed 3 years ago.
I’m trying to print a string, only for 1 second.
The first thing I looked for was a method for deleting a line of console - terminal, But don't find anything.
Then try to backspace 5 times for example for “hello” then print another string like “ ” to delete hello string, but I couldn’t find out how \b works for java.
Now I'm confused, how I actually can solve my problem.
Any idea for backspace?
Or deleting something that's already printed?
Yor can do it by writing carriage return character \r in equal number of the length of already printed string. It will place the cursor back but will not clear the line but as you will write new characters older will be cleared.
I'm not sure to exactly understand what you need, I hope this code will help:
class Main {
public static void main(String[] args) throws InterruptedException {
String text = "123456";
System.out.print(text);
Thread.sleep(1000);
backspace(text.length());
Thread.sleep(1000);
System.out.print(text);
Thread.sleep(1000);
arrowLeft(3);
Thread.sleep(1000);
System.out.print(text);
}
public static void backspace(int number){
for(int i=0; i<number; i++){
System.out.print("\b \b");
}
}
public static void arrowLeft(int number){
for(int i=0; i<number; i++){
System.out.print("\b");
}
}
}
Related
This question already has answers here:
What is a debugger and how can it help me diagnose problems?
(2 answers)
Closed 1 year ago.
public class Main {
public static void main(String[] args) {
permutationWithRepeation("PQR");
}
private static void permutationWithRepeation(String str1) {
System.out.println("The given string is: PQR");
System.out.println("The permuted strings are:");
showPermutation(str1, "");
}
private static void showPermutation(String str1, String NewStringToPrint) {
if (NewStringToPrint.length() == str1.length()) {
System.out.println(NewStringToPrint);
return;
}
for (int i = 0; i < str1.length(); i++) {
showPermutation(str1, NewStringToPrint + str1.charAt(i));
}
}
}
I am not able to understand after PPP
The output of the code is
The given string is: PQR
The permuted strings are:
PPP
PPQ
PPR
PQP
PQQ
PQR
PRP
PRQ
PRR
QPP
QPQ
QPR
QQP
QQQ
QQR
QRP
QRQ
QRR
RPP
RPQ
RPR
RQP
RQQ
RQR
RRP
RRQ
RRR
The main idea is recursion. On each recursion level you put character at next position. Loop at each level is used to put all possible characters at next position and to go into next recursion level. When all characters are set your string has length 3 and recursion stops.
I want to print a progress bar like so:
[# ] 1%
[## ] 10%
[########## ] 50%
But these should all be printed to the same line in the terminal instead of a new one.
What I mean by that is that each new line should replace the previous, it's not about using print() instead of println().
How can I do that in Java?
Format your string like so:
[# ] 1%\r
Note the \r character. It is the so-called carriage return that will move the cursor back to the beginning of the line.
Finally, make sure you use
System.out.print()
and not
System.out.println()
In Linux, there is different escape sequences for control terminal. For example, there is special escape sequence for erase whole line: \33[2K and for move cursor to previous line: \33[1A. So all you need is to print this every time you need to refresh the line. Here is the code which prints Line 1 (second variant):
System.out.println("Line 1 (first variant)");
System.out.print("\33[1A\33[2K");
System.out.println("Line 1 (second variant)");
There are codes for cursor navigation, clearing screen and so on.
I think there are some libraries which helps with it (ncurses?).
First, I'd like to apologize for bringing this question back up, but I felt that it could use another answer.
Derek Schultz is kind of correct. The '\b' character moves the printing cursor one character backwards, allowing you to overwrite the character that was printed there (it does not delete the entire line or even the character that was there unless you print new information on top). The following is an example of a progress bar using Java though it does not follow your format, it shows how to solve the core problem of overwriting characters (this has only been tested in Ubuntu 12.04 with Oracle's Java 7 on a 32-bit machine, but it should work on all Java systems):
public class BackSpaceCharacterTest
{
// the exception comes from the use of accessing the main thread
public static void main(String[] args) throws InterruptedException
{
/*
Notice the user of print as opposed to println:
the '\b' char cannot go over the new line char.
*/
System.out.print("Start[ ]");
System.out.flush(); // the flush method prints it to the screen
// 11 '\b' chars: 1 for the ']', the rest are for the spaces
System.out.print("\b\b\b\b\b\b\b\b\b\b\b");
System.out.flush();
Thread.sleep(500); // just to make it easy to see the changes
for(int i = 0; i < 10; i++)
{
System.out.print("."); //overwrites a space
System.out.flush();
Thread.sleep(100);
}
System.out.print("] Done\n"); //overwrites the ']' + adds chars
System.out.flush();
}
}
You could print the backspace character '\b' as many times as necessary to delete the line before printing the updated progress bar.
package org.surthi.tutorial.concurrency;
public class IncrementalPrintingSystem {
public static void main(String...args) {
new Thread(()-> {
int i = 0;
while(i++ < 100) {
System.out.print("[");
int j=0;
while(j++<i){
System.out.print("#");
}
while(j++<100){
System.out.print(" ");
}
System.out.print("] : "+ i+"%");
try {
Thread.sleep(1000l);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.print("\r");
}
}).start();
}
}
One could simply use \r to keep everything in the same line while erasing what was previously on that line.
In kotlin
print()
The print statement prints everything inside it onto the screen.
The print statements internally call System.out.print.
println()
The println statement appends a newline at the end of the output.
You can just do
System.out.print("String");
Instead
System.out.println("String");
This question already has answers here:
Print character multiple times [duplicate]
(5 answers)
Closed 2 years ago.
I'm assigned to write a program which prints (x) amount of "*" in a row.
I tried using the "*".repeat(amount) command, but the software wont accept it as a solution.
Also tried using for and while -loops, but I can't figure how to get the *'s be on the same row.
public class Tulostelua {
public static void main(String[] args) {
printStarts(3);
}
public static void printStart(int amount) {
}
}
You could either use print (which doesn't start a new line) or add the chars to a string and println that.
So if I understand your question correctly, you need something like this:
public void print(int amount) {
for(int i = 0; i < amount; i++) {
System.out.print('*');
}
}
This question already has answers here:
Reverse a string in Java
(36 answers)
Closed 5 years ago.
I am having a slight issue with my String Reverse code, and I cannot seem to fix it. I have made a different way that works, involving a for-loop, and that seems to work fine. However, when I run this code, it always gives me a "null" before the reversed String. For example, when I run this and input "StackOverflow", I get an output of null wolfrevOkcatS" (without the Space). I do not understand why an error like this would happen, so I also added a "null" checker, which did not seem to work. For this null checker, I converted the char into an Ascii value before putting it into my reversed string, and then checked if it was 0. (The ascii value of null) However, this did not seem to work, so I did some research, and could not find anything on Overflow, so decided to ask this question. Sorry and apologies in advance if this is a very "dumb" question, as I am quite new to java, and do not know who to ask.
Thanks in advance,
- A novice Java Coder
import java.util.Scanner;
public class StringReverser
{
static String input, reversed;
int i;
public static void main(String[] args)
{
StringReverser ansh = new StringReverser();
ansh.grab();
ansh.reverse(input);
}
public void grab()
{
System.out.println("Enter a word to be reversed: ");
Scanner kys = new Scanner(System.in);
input = kys.next();
i = input.length();
}
public void reverse(String word)
{
if(i == 0)
{
System.out.println(reversed);
}
else
{
//if((int)(word.charAt(i-1)) == 0)
//{i--; reverse(input);}
reversed+=word.charAt(i-1);
i--; reverse(input);
}
}
}
That's because reserved is initialized to null by default.
if(i == 0)
{
System.out.println(reversed);
}
This question already has answers here:
How to use .nextInt() and hasNextInt() in a while loop
(3 answers)
Closed 6 years ago.
I have this code that I want to run to solve a problem which needs a three user inputs, and I used Scanner class for this:
public static void main(String[] args) {
int M = 0;
int A = 0;
Scanner input = new Scanner(System.in);
System.out.println("Please, insert the normal dose in ml:");
M = input.nextInt();
System.out.println("Please, insert the set of experiments (3 integers per line, stop by 0 0 0):");
try {
while (input.hasNextInt()) {
System.out.print(input.hasNext());
int i = input.nextInt();
A += i;
System.out.println(A);
}
} catch (Exception x) {
System.out.print(x.getMessage());
}
System.out.println("Loop ended");
}
The strange thing is that input.hasNextInt() gets stuck or something after I Insert the three values, It seem that it keeps looping or something even though there are no inputs in the console, can some one provide some help for me?
That's because input.hasNextInt() waits until a integer value is available. It would return false if an alphanumeric value was informed.
You have to define another way to break while loop, maybe with a counter or, like your message says, checking whether 3 values are equal to 0.