Java: Moving the Console cursor up a line - java

First let me clear out i am new to programming and hope that i am using the right terminology.
I using the System.out.print(""); Method to print to the Windows Console:
System.out.print("Backspace b"); //Output: Backspace b
So the cursor is now "behind" the b, if i type in System.out.print("\b"); the curser moves one to the left, deleting the "b". -->
System.out.print("Backspace b"); //Output: Backspace b
System.out.print("\bh"); //Output: Backspace h
Now if i Type in System.out.print("\n\bh"); the output isn't Backspace bh but:
"Backspace b
h"
How can i manage that the cursor goes back one line "up" and to it's far right. Something line a "minus \n" or "not \n", so that it reads Backspace bh?
Is there something like that in Java?

It's impossible without third party libraries. I've done extensive research on this as I've been working on console games for the past week and from what I can tell you can either require JNI, JNA, Jansi, or JLine which will require Jansi or JNA. Personally I recommend JLine as all the others will require you to write C or C++.
If you say want to go up so many lines you could do something like this with JLine.
import org.jline.terminal.Terminal;
import org.jline.terminal.TerminalBuilder;
import org.jline.utils.InfoCmp;
import java.io.IOException;
public class CursorStuff
{
static Terminal terminal;
public static void main(String[] args) throws IOException
{
terminal = TerminalBuilder.terminal();
System.out.println("1");
System.out.println("2");
System.out.println("3");
System.out.println("This line will get overwritten by the terminal path");
goBackLines(3);
System.out.println("back 3 overwriting 2");
}
public static void goBackLines(int remove)
{
for(int i = 0; i < remove; i++)
{
terminal.puts(InfoCmp.Capability.cursor_up);
}
}
}

Related

Why do I get 'Bash (input): command not found' error when using a string for the input, but when I change that part of the code to integers, it works?

I have this program that I'm writing that mainly runs similar to a simple choose your own adventure game. It's a trouble shooting guide for rocketry, that mainly for personal use. It has simple value inputs, y/n, a,b,c,d, and so on. After a few different segments I decided to ask the user (incase I give it to friends or something) if they would like to hear a tip, if they said yes, the tip would be printed out, if not, the program would continue running. When I tested it, i got the error message: 'bash y: command not found'.
All of the syntax is correct (that was the best answer I could find to try to correct the problem, didn't apply), and I don't know what bash is, and I'm using replit, incase that matters.
I get this error in two different areas, but here is an example of one:
//problem code
class A{
public static void tip(){
Scanner scan = new Scanner(System.in);
System.out.println("Would you like to hear a tip? (y/n)");
String tipA = scan.nextLine();
if (tipA.equals("y")){
System.out.println("blahblahblah");
}
}
}
//there was a typo in this post but not in the actual code, wish it was the actual problem, thanks for pointing it out
Then I changed it to this:
//the 'fixed' code
class A{
public static void tip(){
Scanner scan = new Scanner(System.in);
System.out.println("Would you like to hear a tip? (y(1)/n(2))");
int tipA = scan.nextInt();
if (tipA == 1){
System.out.println("blahblahblah");
}
}
}
It works, but as you can see in the 'fixed' code, the y/n doesn't look as nice, and I am also curious as to why, because I could not find any answers pertaining to this scenario.
The other area is similar, but instead of "y/n", it is 'A, B, C, D' choices.
I have my current workaround, but it would be nice to have a solution to polish the program a bit.
Any help is much appreciated.
It sounds like your problem is confusion about what nextLine does. It doesn't do what 99% of java programmers (and most tutorials) think it does. It's not a bug - it does exactly what the javadoc says, but, it's not what you'd expect.
See This answer that explains precisely what to do. Boils down to:
public static void tip() {
Scanner scan = new Scanner(System.in);
scan.useDelimiter("\\R");
System.out.println("Would you like to hear a tip? (y/n)");
String tipA = scan.next();
if (tipA.equals("y")) {
System.out.println("blahblahblah");
}
Generally you'd want to make a scanner exactly once (in your main method perhaps), create a new instance of your Main class, set up the Scanner as a field of it, and then reuse it in all your methods. This saves typing, is easier to test, more flexible, etc:
public class ExampleMain {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
s.useDelimiter("\\R");
ExampleMain app = new ExampleMain();
app.scanner = s;
app.go();
}
private Scanner scanner;
private boolean running;
void go() {
running = true;
while (running) {
tip();
// whatever other commands and such you'd like go here
}
}
void tip() {
System.out.println("Would you like to....");
}
}
This also lets you do things like write a method that repeatedly asks for a specific kind of input (say, an integer between 1 and 9, as you're showing a menu with 9 options), and, using a while loop, keep asking if the user fails to enter appropriate responses. Otherwise you have to copy/paste a ton of code which is naturally not how you should be programming.

Echo class in Java

Please help me with this HW assignment. I am supposed to modify the EchoNumber class which extends the Echo class to count the number of characters in every line in a text file in addition to displaying the text. Here is the Echo class:
import java.util.Scanner;
import java.io.*;
public class Echo{
String fileName; // external file name
Scanner scan; // Scanner object for reading from external file
public Echo(String f) throws IOException
{
fileName = f;
scan = new Scanner(new FileReader(fileName));
}
// reads lines, hands each to processLine
public void readLines(){
while(scan.hasNext()){
processLine(scan.nextLine());
}
scan.close();
}
// does the real processing work
public void processLine(String line){
System.out.println(line);
}
}
Here is the EchoNumber class, notice where it says "Your code goes here":
import java.io.*;
public class EchoNumber extends Echo
{
// the current line number
private int lineNumber;
public EchoNumber (String datafile) throws IOException
{
super( datafile);
lineNumber=1;
}
// Prints a line with a leading line number and a trailing line length
// Overrides the processLine method in Echo class
public void processLine(String line){
/* your code goes here */
}
}
Here is the EchoTester class:
import java.io.*;
import java.util.Scanner;
public class EchoTester
{
public static void main(String[] args)
{
// uses try/catch to handle IOExceptions in main
try
{
String fileName;
Scanner nameReader = new Scanner(System.in);
System.out.println("Enter a file name");
fileName = nameReader.nextLine();
EchoNumber e = new EchoNumber(fileName);
e.readLines();
}
catch(IOException e)
{
e.printStackTrace();
}
}
}
And finally the .txt file:
The best things in life are free
A stitch in time saves nine
Still waters run deep
He teaches ill who teaches all
You can not take it with you when you die
Better untaught than ill taught
Do not cross your bridges before you come to them
Soon learnt soon forgotten
Even a worm will turn
It was the last straw that broke the camels back
The way to a mans heart is through his stomach
If the stone fall upon the egg alas for the egg If the egg fall upon the stone alas for the egg
Where there is a will there is a way
Marry in haste and repent at leisure
One tongue is enough for a woman
If you wish good advice consult an old man
The best advice is found on the pillow
All clouds bring not rain
You can not tell a book by its cover
No news is good news
Bad news travels fast
Live and let live
Birds of a feather flock together
Now is the time
For all good men who actually have the time
To come to the aid of the country in which they live
The output is supposed to be something like:
1 The best things in life are free-32
2 A stitch in time saves nine-27
3 Still waters run deep-21
4 He teaches ill who teaches all-30
5 You can not take it with you when you die-41
6 Better untaught than ill taught-31
7 Do not cross your bridges before you come to them-49
8 Soon learnt soon forgotten-26
9 It was the last straw that broke the camels back-48
Except without spaces between each line. For some reason it fuses into one paragraph if I did not separate each line.
Something like this:
public void processLine(String line){
System.out.println(lineNumber + " " + line + "-" + line.length());
++lineNumber;
}
I haven't tested it, so if it isn't 100% correct, I'll leave it as an exercise for you to complete, but it should put you on the right track. Good luck.
THIS is the correct code. It is important that lineNumber++ is below the print statement!
System.out.println(lineNumber + " " + line + "-" + line.length());
lineNumber++;

why my program never reach the solve method?

sorry if its a stupid question, but I a beginner using StreamTokenizer, I am trying to solve this exercise this, please help me, I dont know what its wrong in my program that never reach my solve method, it also never finishes, I already ask in timus forum, but I know that here is faster to receive an answers
import java.io.*;
public class Prueba {
static int index = 0;
static double[] l = new double[131072];
public static void main(String args[]) throws IOException {
StreamTokenizer str = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
while (((str.nextToken() != StreamTokenizer.TT_EOF))) {
if (str.ttype == StreamTokenizer.TT_NUMBER) {
l[index++] = str.nval;
//System.out.println(str.nval);
// System.out.println(l[0]);
// System.out.println(l[1]);
}
}
solve();
}
public static void solve() {
double res;
for (int i = index - 1; i >= 0; i--) {
res = Math.sqrt(l[i]);
System.out.println(String.format("%.4f\n", res));
}
}
}
You are reading from the standard input, and your code loops until it gets a TT_EOF. To feed a TT_EOF into your program, you need to press Ctrl-D if you're using Unix, or Ctrl-Z followed by Enter if you're using Windows.
You are waiting on System.in, it is blocking on read, ergo, you will never get to EOF so you while loop will continue to wait for input.
As it is, you either need to pipe a file from command line, or enter text on console followed by EOF character. Pressing Ctrl+Z generates EOF in Windows, and pressing Ctrl+D generates EOF in Unix/Linux.
EDIT: If your input is single line you can check for TT_EOL instead of TT_EOF.
You must call eolIsSignificant(true) before entering the loop. This will make sure end-of-line is treated as separate token

java cli running indicator

I want some ascii characters periodically changing to indicate my CLI program is running, like -|\/-|/.... The old character is replaced by the new, which looks like an animation. Is there any library approaching that?
Kejia
You might want to use the carriage return(CR) character ('\r' in java) to do this. I would do it this way (assuming you are doing the animation at the beginning of the row):
My solution (Test.java):
public class Test
{
public static void main(String[] args)
{
try
{
System.out.print("\\");
Thread.sleep(1000);
System.out.print("\r|");
Thread.sleep(1000);
System.out.print("\r/");
}catch(Exception e)
{
}
}
}
Simplest idea: try replace all console (rows & cols) with new view (frame) of your animation.
I once wrote a test program and part of it worked like curl/wget to download a file. To print the progress I just used System.err.print(n); System.err.print('\r'); which moves the cursor to the start of the line ready for the next progress update. But in your case you could probably print each one of "\\\b" "-\b" "/\b" (\b is backspace) in order repetitively to get the spinning effect.
In Scala:
"-|\\/-|/".toCharArray ().foreach {c => print ("\b" + c); Thread.sleep (250); }
Analog, but more Code in Java, but not tested:
for (c : "-|\\/-|/".toCharArray ())
{
System.out.print ("\b" + c);
Thread.sleep (250);
}

count char in java

what is wrong in this code?
import java.io.IOException;
import java.util.*;
public class char_digit {
public static void main(String[] args) throws IOException {
int count=0;
while (true){
char t=(char) System.in.read();
if (t=='0'){
break;
}
count++;
}
System.out.println(count);
}
}
run:
a
b
c
d
e
f
0
12
You're counting the newlines as well as the other characters. Try something like if (t == '\n') continue; before the current if.
nothing is wrong. The carriage return also counts as a char (or 2 depending on your OS)
The problem is that you're counting whitespace characters as well, which are inserted when you hit the Enter button into the console. One quick fix is to use Character.isWhitespace check as follows:
if (t=='0'){
break;
} else if (!Character.isWhitespace(t)) {
count++;
}
Depending on what you want to do, though, a java.util.Scanner may serve your purpose better. Using System.in.read directly is highly atypical, and especially if you're reading char, where a Reader is more suitable.
Related questions
Java I/O streams; what are the differences?
What is the difference between a stream and a reader in Java?

Categories

Resources