How to pad a formatted string - java

This may seem as a simple problem, but I honestly didn't seem to work this out.
I have a formatted string as follows:
String msg = String.format("Current player: %1$s", status.getCurrentPlayer().getName());
and I want to left-pad it, lets say with 10 spaces. I tried:
String pad = String.format("%1$10s", msg);
but it doesn't seem to work, although I tried it with an unformatted string:
String pad = String.format("%1$10s", "some string");
and obviousely, it worked.
What is it about "msg" that does not let me pad it?

What is it about "msg" that does not let me pad it?
It's longer than 10 characters.
That 10 is the width of the Formatter class.
Reading that documentation, you'll see
The optional width is a non-negative decimal integer indicating the minimum number of characters to be written to the output.
So, minimum, meaning any string longer than that are printed as-is.
If you want to pad, just add 10 to the length of the string.
String msg = "some really, really long message";
String fmt = "%1$" + (10 + msg.length()) + "s";
String pad = String.format(fmt, msg);
// " some really, really long message"

String msg = "Current player: "
+ status.getCurrentPlayer().getName()
+ new String(new char[10]).replace('\0', ' ');
This will add 10 spaces after the name of the player. If you want to take into account the length of the player name you can do this:
String msg = "Current player: "
+ status.getCurrentPlayer().getName()
+ new String(new
char[10 - status.getCurrentPlayer().getName().Length ]).replace('\0', ' ');

Related

How do i parse a string to get specific information using java?

Here are some lines from a file and I'm not sure how to parse it to extract 4 pieces of information.
11::American President, The (1995)::Comedy|Drama|Romance
12::Dracula: Dead and Loving It (1995)::Comedy|Horror
13::Balto (1995)::Animation|Children's
14::Nixon (1995)::Drama
I would like to get the number, title, release date and genre.
Genre has multiple genres so I would like to save each one in a variable as well.
I'm using the .split("::|\\|"); method to parse it but I'm not able to parse out the release date.
Can anyone help me!
The easiest would be matching by regex, something like this
String x = "11::Title (2016)::Category";
Pattern p = Pattern.compile("^([0-9]+)::([a-zA-Z ]+)\\(([0-9]{4})\\)::([a-zA-Z]+)$");
Matcher m = p.matcher(x);
if (m.find()) {
System.out.println("Number: " + m.group(1) + " Title: " + m.group(2) + " Year: " + m.group(3) + " Categories: " + m.group(4));
}
(please don't nail me on the exact syntax, just out of my head)
Then first capture will be the number, the second will be the name, the third is the year and the fourth is the set of categories, which you may then split by '|'.
You may need to adjust the valid characters for title and categories, but you should get the idea.
If you have multiple lines, split them into an ArrayList first and treat each one separately in a loop.
Try this
String[] s = {
"11::American President, The (1995)::Comedy|Drama|Romance",
"12::Dracula: Dead and Loving It (1995)::Comedy|Horror",
"13::Balto (1995)::Animation|Children's",
"14::Nixon (1995)::Drama",
};
for (String e : s) {
String[] infos = e.split("::|\\s*\\(|\\)::");
String number = infos[0];
String title = infos[1];
String releaseDate = infos[2];
String[] genres = infos[3].split("\\|");
System.out.printf("number=%s title=%s releaseDate=%s genres=%s%n",
number, title, releaseDate, Arrays.toString(genres));
}
output
number=11 title=American President, The releaseDate=1995 genres=[Comedy, Drama, Romance]
number=12 title=Dracula: Dead and Loving It releaseDate=1995 genres=[Comedy, Horror]
number=13 title=Balto releaseDate=1995 genres=[Animation, Children's]
number=14 title=Nixon releaseDate=1995 genres=[Drama]

how to generate string with varying number of spaces OR how to add no of spaces after a string

I need help to generate empty string with particular no of spaces.
I tried this,
String opCode= " ";
for(int l=0;l<opCodelen;l++)
{
opCode+= " " ;
}
//opCodelen will get change every time
This worked but I want better solution.becoz using this I will have to use multiple loops for multiple columns.Is there any other way to do this?
Try String.format()
int opCodelen = 5;
String opCode = String.format("%" + opCodelen + "s", "");
System.out.println("[" + opCode + "]");
output
[ ]
Another way (uglier but for many probably simpler) to solve it could be
creating array of characters with same length as number of spaces you want to end up with,
filling it with spaces
and passing it as argument in String constructor.
Something like
char[] arr = new char[10]; // lets say length of string should be 10
Arrays.fill(arr, ' '); // fill array with spaces
String mySpaceString = new String(arr);
System.out.println(">" + mySpaceString + "<");
output:
> <

What does this NumberFormatException mean?

java.lang.NumberFormatException: For input string: ":"
What does this mean?
I get the above error if I run the code (below).I am a beginner here.
and..
stacktrace:[Ljava.lang.StackTraceElement;#e596c9
the code:
try
{
Class.forName("java.sql.DriverManager");
Connection con=DriverManager.getConnection("jdbc:mysql://localhost/bvdb","root","enter")
Statement stm=con.createStatement();
String m="-",t="-",w="-",th="--",f="-",st="--",s="-",runson;
if(jCheckBox1.isSelected()==true){
m="m";}
if(jCheckBox2.isSelected()==true){
t="t";}
if(jCheckBox3.isSelected()==true){
w="w";}
if(jCheckBox4.isSelected()==true){
th="th";}
if(jCheckBox5.isSelected()==true){
f="f";}
if(jCheckBox6.isSelected()==true){
st="st";}
if(jCheckBox7.isSelected()==true){
s="s";}
runson= m + t + w + th + f + st + s ;
int h1=Integer.valueOf(jTextField10.getText().substring(0,2)
int mins1=Integer.valueOf(jTextField10.getText().substring(3,5));
int h2=Integer.valueOf(jTextField12.getText().substring(0,2));
int mins2=Integer.valueOf(jTextField12.getText().substring(2,3));
Boolean x=jTextField10.getText().substring(2,3).equals(":");
Boolean y=jTextField12.getText().substring(2,3).equals(":");
String time1=jTextField10.getText().substring(0,2)+jTextField10.getText().substring (2,3)+jTextField10.getText().substring(3,5);
String time2=jTextField12.getText().substring(0,2)+jTextField12.getText().substring(2,3)+jTextField12.getText().substring(3,5);
String tfac1=jTextField13.getText();
String tfac2=jTextField14.getText();
String tfac3=jTextField15.getText();
String tfsl=jTextField16.getText();
if(Integer.valueOf(jTextField3.getText())==0){
tfac1="0";
if(Integer.valueOf(jTextField4.getText())==0){
tfac2="0";}
if(Integer.valueOf(jTextField5.getText())==0){
tfac3="0";}
if(Integer.valueOf(jTextField6.getText())==0){
tfsl="0";}
if(y==true&&x==true&&jTextField1.getText().trim().length()<=6&&jTextField2.getText().trim().length()<=30&&h1<=24&&h2<=24&&mins1<=59&&mins2<=59){
String q="INSERT INTO TRAININFO VALUE ("+jTextField1.getText()+",'"+jTextField2.getText()+"','"+jTextField9.getText()+"','"+time1+"','"+jTextField11.getText()+"','"+time2+"','"+runson+"',"+tfac1+","+tfac2+ ","+tfac3+","+tfsl+","+jTextField3.getText()+","+jTextField4.getText()+","+jTextField5.getText()+","+jTextField6.getText()+");";
stm.executeUpdate(q);
JOptionPane.showMessageDialog("ADDED");
}
}
catch (Exception e){
e.printStackTrace();
}
that means you can not convert the String ":" to Number like integer or double
see below link
http://docs.oracle.com/javase/7/docs/api/java/lang/NumberFormatException.html
According to java docs
Thrown to indicate that the application has attempted to convert a
string to one of the
numeric types, but that the string does not have the appropriate format.
It means you want to convert ":" to a number which is not allowed. Hence you are getting the exception. Better show your code
The best way you get responses faster & answered your question is posting your code.
You cannot convert String to number.
As others have said Java can't convert "15:" into a number because ":" is not a digit. And the most probable cause for this is a line like this one:
int h1 = Integer.valueOf(jTextField10.getText().substring(0,2));
where you are splitting a time string at the wrong index which is why you have ":" in it.
UPDATE
Better way of splitting a time string like "12:35:09" is by using String.split():
String timeString = "12:35:09";
String[] parts = timeString.split(":");
boolean validTimeString = parts.length == 3;
The code above will result in the following values:
timeString = "12:35:09"
parts[0] = "12"
parts[1] = "35"
parts[2] = "09"
validTimeString = true
String.split(DELIMITER) will split the string into N + 1 strings where N is the number of occurences of the DELIMITER in target string.

Using Java String.format

I have a string "name" which I need to add n amount of blank spaces to the end. I have been told to use String.format but for the life of me I cant figure out how to do it.
String formatName = String.format(name, %15s);
return formatName;
But this didn't work, can anyone point me in the right the direction?
Basically I need to make each string 15 characters long with blank spaces appended to the end if the original string is too short.
================
With advice I reversed the paramaters however this throws up an error.
private String format(String name, String number)
{
String formatName = String.format(%15s, name);
String formatNumber = String.format(%15s, number);
return formatName + " - " + formatNumber;
}
However this throws an error - Illegal start of expression.
Can anyone tell me what I'm doing wrong?
formatName = String.format(name + "%15s", "");
OR
formatName = String.format("%-15s", name);
The - appends to the end of the argument.

String format with NumberFormat

I'm formatting a String that i enter in a JTextField using NumberFormat instance without specifying the location. As a result i have a String that represents a number formatted with white spaces as separator. I have a problem to get rid of the white spaces when i want to use the String for other processes. I have tried string.replaceAll(" ", ""); and string.replaceAll("\\s", ""); but none of it works.
String string = ((JTextField)c).getText();
string = string.replaceAll("\\s", "");
Also when i do int index = string.indexOf(" "); or int index = string.indexOf("\\s"); it returns -1, which means that it doesn't find the character.
When i do
for(Character ch : string.toCharArray()) {
System.out.println("ch : " + ch.isSpaceChar(ch))
}
it returns true for the empty char. How is represented a space char in java ?
I tried also
StringBuilder b = new StringBuilder(((JTextField)c).getText());
String string = b.toString.replaceAll("\\s", "");
System.out.println("string : " + string);
It doesn't replace a thing.
Have you tried string = string.replaceAll(" ", "");? - string is immutable.
String string = "89774lf&933 k880990";
string = string.replaceAll( "[^\\d]", "" );
System.out.println(string);
OUTPUT:
89774933880990
It will eliminate all the char other than digits.

Categories

Resources