Printing out to terminal without it scrolling - java

So I have been wondering how to do this for some time, and I thought who better to ask then the SO community.
I apologize in advance if this is a little vague, but I will do my best to get my question across.
We all remember the first time we got caught in a infinite loop with a print statement. The terminal fills up fast, and soon all you see it a bunch of scrolling text...
How do I make it not scroll? What I mean is ... How do I overwrite the line that has already been written.
How can I make my infinite loop with a one line print statement(no more than one new line) only print on one line. Where the terminal does not scroll.
Instead of ....
This is an infinite loop
This is an infinite loop
This is an infinite loop
You just have one line that updates every iteration of the loop.
This is an infinite loop
Thanks for reading, comment if this made absolutely no since. I'll try to clarify in a cloudy world...
PS - What I am doing right now is in C, but it wouldn't hurt to know how to do this in other languages.
Question (0.1)
What if you wanted to update multiple lines in place?
printf("This is some text\n");
printf("This is more text\n");
That would give me two lines and I want to update both of them, but not scroll.

You only need carriage return, not line feed hence you need to use only "\r"
Carriage return means bringing the cursor back to the beginning of the line.
Line feed means feeding a new line to the terminal.
In c :
while(1)
{
printf("\r This is an infinite loop.");
}
Since the printf is buffered, therefore it's a good practice to explicitly flush the output stream.

You may use the carriage return escape sequence, or \r. This will return the cursor to the start of the line.
while (1)
{
std::cout << "\rTest.";
}

Try this...
while(1)
{
printf("this id infinite loop\n");
sleep(1);
system("clear");
}

Related

Not sure why my for loop isn't working the way i intended it to

So, before I start I just wanted to say that I'm very new to Java as a language and I've been reading a text book that was recommended to me.
One of the examples provided within the text book on for loops had the following code, which is meant to generate an infinite for loop until the user presses the character 'S' on their keyboard.
Here is the code:
class ForTest {
public static void main(String args[])
throws java.io.IOException {
int i;
System.out.println("Press S to stop.");
for (i = 0; (char) System.in.read() != 'S'; i++)
System.out.println("Pass #" + i);
}
}
I copied the code exactly as it was written within the book but when I run the program, to my surprise, it doesn't start printing out numbers onto the console. Additionally, whenever I press any keys on the keyboard it generates three numbers within the sequence. Example shown below:
I have also included a screenshot of the code from the book below:
I was wondering whether anyone knows why this is the case!
Any help would be greatly appreciated thanks.
The reason it's printing multiple times is because multiple characters are detected.
In your case, it's printing twice because you entered a value (Pass 1) and a new line (Pass 2)
The problem you have is not with System.in.read(), but because the console is usually using a buffered approach. Meaning that data is only transferred to the System.in.read() once you press enter.
So to get the example working, you would have to switch the console to an unbuffered mode, but there is no portable way to do this, because there are so much different types of consoles. Maybe have a look at what editor/console the book is using
This block of code looks like it was written by someone who was deliberately trying to make it obtuse and difficult to comprehend for a beginner.
The middle expression of a for statement is the criterion for taking the next step of the loop. It is evaluated before each step of the loop to determine whether the for loop is complete yet. In this case, it calls in.read() and checks if the input is S before each step of the loop.
in.read() waits for the next line of input it gets. When you enter a value and press Enter, that line gets read, so the loop takes a step. And a new line is also entered, so the loop takes a second step.
It will not print lines to the console unless you enter lines, because in.read() causes the program to block (wait) for the next input.

Having issue with the concept of extra semi-colon at the end of for loop in Java

I was writing a code to insert an element at the end of the linked list. However without using the semi-colon at the end of for, I'm unable to get the list updated properly, what is the significance of this semi-colon and how is this affecting my code?
public void insertAtEnd() throws IOException {
LinkedList node=new LinkedList();
System.out.println("Enter an element");
int value=Integer.parseInt(br.readLine());
node.setData(value);
LinkedList p,q;
for(p=head; (q=p.getNext())!=null; p=q);
p.setNext(node);
}
The semicolon means that the statement below won't be executed until the loop has exited. Your case, the loop is taking p to the end of the list (the last element) and then the next statement is assigning its next value to the new element
Well, the way it is constructed right now as for(p=head; (q=p.getNext())!=null; p=q);, the for loop has an empty body. The variables p and q through the p.getNext() and p=q assignments are updating. Then it is executing the p.setNext(node); a single time.
EDIT: As to why the code is working with the semi-colon, it is because you are advancing the variables p and q over the list. While the for loop with the empty body is fine, I think traditionally one sees a while loop.
The indentation of the p.setNode(node); makes it appear as if the statement were related to the for loop, but it really isn't, as the goal is to find the end of the linked list by iterating over it.
(note: others made similar points while I was typing this answer)
it needs to be removed, it is causing it to do nothing in the loop.
The loop will execute the next single block of code after the loop. Either one statement, or one { } code block.
In this case, you have one statement ;, so it "executes" and does nothing, and then will call your p.setNext(node); after the loop ends.
public void insertAtEnd() throws IOException {
LinkedList node=new LinkedList();
System.out.println("Enter an element");
int value=Integer.parseInt(br.readLine());
node.setData(value);
LinkedList p,q;
for(p=head; (q=p.getNext())!=null; p=q)
p.setNext(node);
}
The semicolon is essentially transforming what you appear to want to do because of your indentation:
for(p=head; (q=p.getNext())!=null; p=q)
{
p.setNext(node);
}
into the following:
for(p=head; (q=p.getNext())!=null; p=q)
{
}
p.setNext(node);
So with the semicolon your loop is executing nothing at every iteration. Then, after it has finished executing, you're running p.setNext(node); exactly once.
Usually you can avoid this problem in the future by explicitly writing your curly braces as I have done in these two code segments. It is unclear exactly which code segment you are trying to accomplish right now.
The for statement provides a compact way to iterate over a range of values. Programmers often refer to it as the "for loop" because of the way in which it repeatedly loops until a particular condition is satisfied. The general form of the for statement can be expressed as follows:
for (initialization; termination; increment) {
//statement(s)
}
When using this version of the for statement, keep in mind that:
The initialization expression initializes the loop; it's executed once,
as the loop begin
When the termination expression evaluates to false, the loop terminates.
The increment expression is invoked after each iteration through the loop; it is perfectly acceptable for this expression to increment or decrement a value.
In your case, the loop is taking p to the end of the list (the last element) and then the next statement is assigning its next value to the new element

How can I make my for loop execute tasks completely before going on to the next iteration? [duplicate]

This question already has answers here:
System.out.println and System.err.println out of order
(7 answers)
Closed 8 years ago.
I am trying to parse a file at work but for some reason my for loop does not execute an entire iteration of tasks before going on to the next iteration.
I have a sample code here that shows the same issue and I think that if I can fix this simple example I will be able to fix my more complex issue at work.
Sample code :
package loops;
public class Loops {
public static void main(String[] args) {
System.out.println("here goes");
for(int i=0;i<1000;i++){
System.err.println(i);
if(i==i){
System.out.println(i+1);
}
}
}}
The above code runs and prints the iteration of the loop "i" in red. It goes through the if statement and prints the i+1 in black. My issue is that instead of being red black red black it finishes the if statements long before it finishes the for loop "i" printouts. Is there any way to make this loop go in order? I have tried to make it sleep after each iteration but that does not fix it.
Thanks.
This because both System.out and System.err could be buffered streams. This means that writes are not executed right when data is placed onto the stream but rather in chunks.
Try to flush the output right after each print:
System.out.println(...);
System.out.flush();
In this way you will force the stream to flush their buffer before executing other instructions. This may come with a performance cost.
Stdout is buffered, stderr isn't. Print both to stdout or both to stderr, don't mix them.

Java one line if statement [duplicate]

This question already has answers here:
Is it ok if I omit curly braces in Java? [closed]
(16 answers)
Closed 9 years ago.
I am using if condition without braces in java something like
if(somecondition)
//Only one line Business logic
but some told use braces always even one line statement something like this
if(somecondition){
//Only one line Business logic
}
What is the better way according to java sandard?
there's no real "standard". i prefer always using braces because if you dont you risk someone adding an innocent looking logging statement turning your code from
if(somecondition)
//Only one line Business logic
into
if(somecondition)
log.debug("condition was true");
//Only one line Business logic
and then things stop working :-)
That's a matter of taste. I would use braces or else no braces but write all code in one line to improve readability.
Also you might consider using a ternary operator
booleanExpression ? value1 : value2
In addition to #radai answer, if you are a real evil mind, when you see a if with no braces you can do something that will make you ennemies by adding a semi-colon on the same line of the if but at the 800th column of the line(or something).
like
if(condition) /*a loooot of whitespace*/ ;
//Only one line Business logic that will get executed whatever is the condition
This is why i prefer to use braces and recommend people to use them
No naked if statements. You're just asking for trouble. Always use { }
it is better to use braces when checking for errors or updating the code.
imagine.
if(answer.equals("add"))
addedValue += Scanner.readInt();
but you have a new requirement to add only the absolute value, so you change to.
if(answer.equals("add2))
valueToBeAdded = Scanner.readInt();
if(valueToBeAdded < 0) valueToBeAdded = - valueToBeAdded;
addedValue += valueToBeAdded;
this is not a really correct algorithm, is just an example of what can happens.
Using if statement with braces is better way to java standard, because it increase the readability and reduce unwanted error.
The two statements have exactly the same effect but I have suffered so often from the lack of braces that I also always comment that there should be braces even around 1 line statements. This makes the code easier to maintain and can save a lot of headache. My experience shows that one line if statements often turn into multi-line statements on later iterations so what you save by not writing two { the first time, you will give later on.
According to java standard braces are better because if they are not there compiler has to work around more and also would be performance issue.

do-while loops with continue and with and without a label in Java

Let's look at the following do-while loop. It's quite obvious and there is no question about it.
do
{
System.out.println("Hello world");
break;
} while(false);
It's quite obvious and just displays the string Hello world on the console and exits.
Now, the following version of do-while seems to be getting stuck into an infinite loop but it doesn't. It also displays the string Hello world on the console and exits silently.
do
{
System.out.println("Hello world");
continue;
} while(false);
Let's see yet another version of do-while with a label as follows.
label:do
{
System.out.println("Hello world");
continue label;
} while(false);
It too displays the message Hello world on the console and exits. It's not an infinite loop as it may seem to be means that all the versions in this scenario, work somewhat in the same way. How?
The continue statement means "proceed to the loop control logic for the next iteration". It doesn't mean start the next loop iteration unconditionally.
(If anyone wants to refer to the JLS on this, the relevant section is JLS 14.16. However, this part of the specification is a bit complicated, and depends on the specifications of other constructs; e.g. the various loop statements and try / catch / finally.)
Just like with a for loop, the while conditional in a do-while is always checked before entering the loop body (after the first pass through, of course). And, just like with a for loop, continue never causes the termination expression to be skipped.
The continue is checking the boolean expression before actually continuing, as the manual says:
The continue statement skips the current iteration of a for, while , or do-while
loop. The unlabeled form skips to the end of the innermost loop's body and
evaluates the boolean expression that controls the loop.
For more details have a look at: branching semantics

Categories