Update Java multiple-line console output without adding new lines [duplicate] - 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

How can I repeat a method with a variable integer?

I just started learning how to program in Java a month ago. I am trying to make my robot (karel) put a beeper the amount of times that is indicated in the "put" integer only, not the total amount the object has. However, it is not a set number and karel.putBeeper(put); does not get accepted in the compiler due to the class not being applied to given types. Any help would be greatly appreciated, and I am starting to understand why Stack Overflow is a programmer's best friend lol. Note: I might not respond to to any helpful tips until tomorrow.
import java.io.*;
import java.util.*;
public class Lab09 {
public static void main(String[]args) {
Scanner input = new Scanner(System.in);
System.out.println("Which world?");
String filename = input.nextLine();
World.readWorld(filename);
World.setSize(10,10);
World.setSpeed(6);
Robot karel = new Robot(1,1,World.EAST,0);
int pick=0;
int put=0;
for(int i=0; i<8; i++) {
while(karel.onABeeper()) {
karel.pickBeeper();
pick++;
karel.move();
}
for(i=0; pick>i; pick--) {
put++;
}
if(!karel.onABeeper()) {
karel.move();
}
while(karel.onABeeper() && put>0) {
karel.putBeeper(put);
}
}
}
}
If I got your question right, you're trying to putBeeper put times, which is done by the following code:
while (karel.onABeeper() && put > 0) {
karel.putBeeper(put);
}
The issue I see here is that you're not changing the value of put after calls to putBeeper, hence this while loop will never terminate: for instance, if the value of put was 5 during the first loop iteration, it will always remain 5, which is larger than 0. Also, as you've mentioned, putBeeper doesn't take any arguments, hence trying to pass put as an argument won't work - the compiler catches that error for you.
If your intent is to call putBeeper put times then what you can do is decrement put after every invocation of putBeeper - put will eventually reach 0, at which point you've called putBeeper exactly put times. And since you're just learn to program in Java, I'll leave the actual implementation to you as an exercise. Good luck!

what is a console in java?

I am new to programming and learning Java.
I was looking at an old code and they used something called a console. When I copy-pasted the code, Java did not read anything called a console. Is a console basically a scanner? I searched online and they said it's for input, so should I just remove all consoles and write scanner there instead?
Scanner as in writing Scanner scan = new Scanner(System.in);
I am using the latest version of Java.
(Yes, this for a game of crazy eights)
This is just a part of the old code :
// The "CrazyEights" class.
import java.awt.*;
import hsa.Console;
public class CrazyEights
{
static Console c; // The output console
static int[] deck, player, computer; // card arrays
static int pile, suit; // discard pile, current suit (0-3)
static boolean deckEmpty;
public static void main(final String[] args)
{
// setup console
c = new Console(30, 100, "Crazy Eights");
intro(); // splash page, instructions
char playAgain;
do
{
c.setFont(new Font("Arial", java.awt.Font.PLAIN, 14));
game();
c.setCursor(30, 32);
playAgain = c.getChar();
} while ((playAgain == 'y') || (playAgain == 'Y'));
c.close();
}
}
The specific Console you are asking for is in your imports.
There is an import "import hsa.Console" on the top of your code. If you are not familiar with imports, as you say you are new to programming/Java, it signifies that when you write "Console" inside this file ("CrazyEights.java") you are referencing the "Console" defined in "hsa.Console".
Now, since this class is specific to your project, we can't know what it is and does. You will have to open it and see for yourself.
However, with a quick search, you are probably using "ReadyToProgram" IDE for Java by Holtsoft and Associates and that's what the prefix hsa stands for in "hsa.Console".
If you are not using that and just copy-pasted the code expecting it to work, it won't. That import is not in the standard Java library. You will need to find it, download it and add it to your project dependencies. If you did that just to start somewhere with Java and it is not essential to you, I would suggest leaving this block of code and moving somewhere else.

Can someone tells me what's the logical error in this code?

LOGICAL ERROR: The output works fine and produces the 1st output, and when checked with the 2nd output, it produces the first statement Kids: 6, but the second statement New baby, kids now: 7 is never produced and instead, New baby, kids now: 4 is produced.
HINT: The hint given to me is that changes must be made in the specific lines of the code ONLY. You can see the code, it is mentioned there that the changes must be made in callPersonInfo.java only and that too in-between these lines //changes must be made after this line. So NO changes above this line. and //changes must be made above this line. So NO changes below this line. Rest of the code is fine.
Expected 1st output:
Kids: 3
New baby, kids now: 4
Expected 2nd output: (NOT part of 1st output, but it should work with this as well just to check reliability of the code)
Kids: 6
New baby, kids now: 7
Code: (Runs fine, but logical error)
// ===== Code from file PersonInfo.java =====
public class PersonInfo {
private int numKids;
public void setNumKids(int personsKids) {
numKids = personsKids;
return;
}
public void incNumKids() {
numKids = numKids + 1;
return;
}
public int getNumKids() {
return numKids;
}
}
// ===== end =====
// ===== Code from file CallPersonInfo.java =====
public class CallPersonInfo {
public static void main (String [] args) {
PersonInfo person1 = new PersonInfo();
person1.setNumKids(3);
//changes must be made after this line. So NO changes above this line.
System.out.println("Kids: " + person1.getNumKids());
person1.setNumKids(4);
System.out.println("New baby, kids now: " + person1.getNumKids());
//changes must be made above this line. So NO changes below this line.
return;
}
}
// ===== end =====
You're setting the value of numKids each time and not incrementing (adding to) it as you want to.
Call incNumKids() instead of setNumKids(4) and you'll add 1 to the number pass in on the first call of setNumKids().
Note: What's not made clear in question is that that person1.setNumKids(3) isn't actually a static piece of code, and that you're apparently also editing this to get the initial "Kids: X" output.

Jansi keeps incrementing indentation

I can't seem to get rid of previously printed lines. If I do just
AnsiConsole.out.println(ansi);
It repeats the same output every successive output. E.g.
A
AB
ABC
Even if the output is only supposed to be
A
B
C
My code is:
AnsiConsole.out.println(a);
a.eraseLine(Erase.ALL);
AnsiConsole.out.flush;
If I don't use a.eraseLine(Erase.ALL), it looks like this:
Also, if I don't use Jansi and use plain System.out, it looks like this so I know it's not a matter of code elsewhere.
Solution:
Thanks to Betlista's answer. I found out what was wrong. The thing was that my ansi variable was actually called using the Ansi constructor and not the Ansi.ansi() method. That was what was different in my code. Thanks. :)
It seems you are doing something wrong, but there is a lot of info missing in your post, that it is hard to follow...
...so I'll write how it works for me:
I'm using maven with jansi in version 1.11 tested on Windows 7.
I simply followed the info on https://github.com/fusesource/jansi and my code
package jansi;
import java.io.IOException;
import org.fusesource.jansi.Ansi;
import org.fusesource.jansi.Ansi.Color;
import org.fusesource.jansi.AnsiConsole;
public class Main {
public static void main(String[] args) throws IOException {
AnsiConsole.systemInstall();
String[] sa = {"A", "B", "C"};
Color[] ca = {Color.RED, Color.GREEN, Color.BLUE};
for (int i = 0; i < sa.length; ++i ) {
System.out.println(Ansi.ansi().eraseLine().fg(ca[i]).a(sa[i]).reset());
}
}
}
is doing exactly what I expected and this is the result:

Printing individual parts of an array in a Java Gui app

OK, so I created a console app that, among other things, takes an array of numbers and prints them out one by one, line by line. Now, I have to take the class that I created for that console app, and pop it into a separate GUI app we're creating. I have all of the other methods working fine, but for the life of me I cannot get the array method to print out correctly. It just gives me the last number I typed into the text field. I'm hoping someone can give me a nudge to help me figure this part out so I can move along, and get to the whole SpringLayout stuff, (the main part of the new assignment) I am limited in what I can show you here because this is a current assignment, so I will have to stick to this stuff as specifically as I can. And please, don't just post the code as an answer, (because then I can't use it), thanks.
Here's what I had for my original project for the array method:
int [] getArray(int x)
{
breakUpNum(x);
return numAry;
}
From there, inside my new class I have this, in an attempt to get it to print:
private class ButtonTest implements ActionListener
{
public void actionPerformed(ActionEvent ae)
{
Lab1 tester = new Lab1();
int[] test4 = tester.getArray(num);
for(int i = 0; i < test4.length; i ++)
{
crossTest.getArrCross.setText("" + test4[i]);
}
}
}
Any help pointing me in the right direction would be greatly appreciated, thanks!
setText does just that, sets the text you pass to as the current text content, it does not append it.
If you were to use JTextArea, you could use it's append method...however, for a JTextField you need to have a different approach.
Now you could use getArrCross.setText(getArrCross.getText() + test4[i])...but to quite frank, that's rather inefficient, as each call to setText is going to stage a paint event...
StringBuilder sb = new StringBuilder(128);
for(int i = 0; i < test4.length; i ++)
{
sb.append(test4[i]);
}
crossTest.getArrCross.setText(sb.toString());
Now, if you want to separate each element, you need to add
if (sb.length() > 0) {
sb.append(", ");
}
Before sb.append(test4[i]);
The last bit of actionPerformed in the for loop isn't working right. setText replaces the current text with its argument, and it doesn't seem like you want to do that. To fix it, replace the line in the for loop with this:
crossTest.getArrCross.setText(crossTest.getArrCross.getText() + test4[i]);

Categories