I would like to write a character to the same location in a console window.
The characters I would like to write are / - \ _. This will get me a little spinner I can display to show progress or loading.
How can you write the chars to the same location though? Otherwise, you will wind up with something like this /-\_/-\_/-\
With Java 6 you can use the Console to do something like this:
class Main {
public static void main(String[] args) throws InterruptedException {
String[] spinner = new String[] {"\u0008/", "\u0008-", "\u0008\\", "\u0008|" };
Console console = System.console();
console.printf("|");
for (int i = 0; i < 1000; i++) {
Thread.sleep(150);
console.printf("%s", spinner[i % spinner.length]);
}
}
}
\u0008 is the special backspace character. Printing that erases the last character on the line. By starting to print a | and then prepending the \u0008 before all other characters you get the spinner behavior.
Note that this might not be 100% compatible with all consoles (and that System.console() can return null).
Also note that you don't necessarily have to use the console class, as printing this sequence to standard output commonly works just as well.
I don't think Java natively allows for that. You need to use some external library - maybe JCurses can help you.
Related
I'm using inputstreamer to retrieve the output of a shell command running continuously providing an output.
I've managed to isolate a part of the shell output by printing it here: System.out.println(inputStr.substring(inputStr.lastIndexOf(" ")+1));
However, I'd like to store the output in either of two arrrays, depending on the expression of the shell output.
Say we have two shell outpust that follows this syntax: IP 192.168.0.12.4588 > 212.98.120.24.443 psx 4488 as the first one, and the opposite: IP 212.98.120.24.443 > 192.168.0.12.4588 psx 12
From the above print, I can isolate and print both 4488 as well as 12. But if 192.168.0.x.x is the first IP, the value 4448 to be stored in a specific array. Likewise, if > 192.168.0.x.x is on the other side, I want to store the value 12 in a different array.
How would I go about that?
You could do something like this:
public static void main(String[] args)
{
String temp = "IP 212.98.120.24.443 > 192.168.0.12.4588 psx 12";
if(temp.matches(".*192\\.168\\.0\\..*>.*"))
{
System.out.println("1st");
//your code here
}
else if(temp.matches(".*>.*192\\.168\\.0\\..*"))
{
System.out.println("2nd");
//your code here
}
}
I have a requirement to edit the .bat file with Java.
The file contains following line of text
testrunner.bat -ParId=12810 -PsysDate=2014-07-03 "C:\SOAP METHODS\DELINQ-soapui-project.xml"
Here I have a string -ParId=12810 and -PsysDate=2014-07-03, in this I need to write the new content after = sign, i.e. I need to assign different values to -ParId and -PsysDate variables.
What's wrong with rewriting the complete file?
I don't know much about regex, in fact i almost never used it, but you can utilizing regex for your problem, something like:
class RegexExample {
public static void main(String[] args) {
String input = "testrunner.bat -ParId=12810 -PsysDate=2014-07-03 'C:\\SOAP METHODS\\DELINQ-soapui-project.xml'";
input = input.replaceAll("ParId=[0-9]+","ParId=newValueID");
input = input.replaceAll("PsysDate=\\w+\\-\\w+\\-\\w+","PsysDate=newValueDate");
System.out.println(input);
}
}
I know it is not the most efficient or pretty, but you can start from there, many references found in Google though :)
If the file always contains the same text(without the parameters) you could do:
String formatstr = "testrunner.bat -ParId=%d -PsysDate=%s \"C:\SOAP METHODS\DELINQ-soapui-project.xml\"";
String output = String.format(formatstr,id,datestring);
// write output to file
Newbie question comming up. Trying to get my head around JAVA.
How do I print out the content of the reference and not just their postition ? My program is ment to get some text in from the user, and print it out in a reverse order.
Here is my program (so far):
package myProgram;
import javax.swing.JOptionPane;
public class someRandomClass {
public static void main(String[] args) {
String word = JOptionPane.showInputDialog("Write som text here");
StringBuilder outPut = new StringBuilder();
for (int i = word.length()-1; i>=0; i--){
outPut.append(i);
}
System.out.println(outPut.toString());
}
}
I am greatfull for any help and tips! :)
In the line
outPut.append(i);
you are appending the value of your loop counter. You surely mean
outPut.append(word.charAt(i));
You seem to appending the integers instead of the appropriate characters. Try this instead:
outPut.append(word.substring(i, i + 1))
This way, the individual characters of word are appended to your StringBuilder. Note that the append method could also take a char as an argument, so you are also able to use word.charAt(i).
So, you want to emit the character at the position? Try using String.charAt.
outPut.append(word.charAt(i));
I'd probably avoid that and just index the char[] from String.toCharArray, though.
To be honest, I'd avoid doing the reversal loop manually to begin with... try something as follows:
final String word = JOptionPane.showInputDialog("Enter text below");
System.out.println(new StringBuilder(word).reverse());
StringBuilder.reverse should do the work for you (likely in a more efficient way, too). You also don't need to call toString manually, as println will do that for you.
Wondering how I can place the '$' sign so it moves with the number when i do this:
System.out.printf("$%20.2f", test);
i get
$ 10.00
I'm trying to format a series of data into 3 columns
I've tried placing the $ after the % like in C but it doesn't work.
There is no shortcut to add text to the variable to be formatted.
You will have to do this in two steps, like this:
System.out.printf("%20s", String.format("$%.2f", test));
This might be a bit of a kludge but I normally just set up a decimal formatter for this:
import java.text.DecimalFormat;
class Test {
public static void main(String[] args) {
// One-time setup (could be simpler, I've opted for readability).
final String fmt20v2a = "$#################.00";
final String fmt20v2b = "%21s";
final DecimalFormat df20v2 = new DecimalFormat (fmt20v2a);
// Usage
System.out.printf(fmt20v2b + "\n", df20v2.format(74.1));
System.out.printf(fmt20v2b + "\n", df20v2.format(999999.99));
}
}
This gives you aligned output with a bit of extra work, but the setup generally only has to be done once. Output of that is:
$74.10
$999999.99
I know this is silly but I can't overcome my curiosity. Is it possible to write a shell script to format a piece of java code?
For example, if a user writes in a code:
public class Super{
public static void main(String[] args){
System.out.println("Hello world");
int a=0;
if(a==100)
{
System.out.println("Hello world");
}
else
{
System.out.println("Hello world with else");
}
}
}
I would like to write a shell script which would make the code like this.
public class Super
{
public static void main(String[] args)
{
System.out.println("Hello world");
int a=0;
if(a==100){
System.out.println("Hello world");
}
else{
System.out.println("Hello world with else");
}
}
To be precise, we should change the formatting of flower brackets. If it is try/catch or control structures we should change it to same line and if it is function/method/class it should come in next line.I have little knowledge about sed and awk which can do this task so easily. Also I know this can be done using eclipse.
Well, I've had some free time on my hands, so I decided to relive my good old linux days :]
After reading a bit about awk and sed, I've decided that it might be better to use both, as it is easier to add indentation in awk and parse strings in sed.
Here is the ~/sed_script that formats the source file:
# delete indentation
s/^ \+//g
# format lines with class
s/^\(.\+class.\+\) *\({.*\)$/\1\n\2/g
# format lines with methods
s/^\(public\|private\)\( \+static\)\?\( \+void\)\? \+\(.\+(.*)\) *\({.*\)$/\1\2\3 \4\n\5/g
# format lines with other structures
/^\(if\|else\|for\|while\|case\|do\|try\)\([^{]*\)$/,+1 { # get lines not containing '{'
# along with the next line
/.*{.*/ d # delete the next line with '{'
s/\([^{]*\)/\1 {/g # and add '{' to the first line
}
And here is the ~/awk_script that adds indentation:
BEGIN { depth = 0 }
/}/ { depth = depth - 1 }
{
getPrefix(depth)
print prefix $0
}
/{/ { depth = depth + 1 }
function getPrefix(depth) {
prefix = ""
for (i = 0; i < depth; i++) { prefix = prefix " "}
return prefix
}
And you use them like that:
> sed -f ~/sed_script ~/file_to_format > ~/.tmp_sed
> awk -f ~/awk_script ~/.tmp_sed
It is far from proper formatting tool, but I hope it will do OK as a sample script for reference :] Good luck with your learning.
A quick, flawed attempt, but one that works on your sample input:
BEGIN {depth = 0;}
/{$/ {depth = depth + 1}
/^}/ {depth = depth - 1}
{prefix = ""; for (i = 0; i < depth; i++) { prefix = prefix " "} print prefix $0 ; }
This is an awk script: place it in a file and do
awk -f awk_script_file source_file
Obvious flaws with this include:
It doesn't catch braceless places where you'd like indentation like
if (foo)
bar();
It will modify the indent depth based on braces in comments and string literals
It won't detect { braces followed by comments
I think this could be done through a simple 'sed' script.
Use 1 variable (bCount) that stores the amount of '{' (opening brackets) - (minus) the amount of '}' (closing brackets)
Then I would go through the file and insert 'tabs' according to the actual count of bracets that are used.
So
public class Super{ //bCount=0
public static void main(String[] args){ //bCount=1
System.out.println("Hello world"); //bCount=2
int a=0; //bCount=2
....and so on
so instert 0 tabs on line 0
1 tab on line 1
2 tabs on line 3 and 4 and so on...
It is definitely possible... I just don't understand why you would want to spend your time doing it? :] There are enough tools to do that and any decent IDE provides a way to re-format the source code (including Eclipse).
For example, to format in Eclipse 3.4 (should be similar in other versions) just right click on your project or a file and select "Source > Format" from the menu.
And if you need to change the way it formats the code, just go to the "Preferences > Java > Code Style > Formatter" and change the template. As far as I know, it is very similar in JDeveloper and NetBeans.
Have a look at the CLI for Jalopy. Jalopy is a pretty powerful source formatter.
Consider using Jindent, which is a "a simple Java Indent Tool using Emacs". It's a free shell script which is a part of the Ptolemy project at Berkeley.