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.
Related
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', ' ');
I can have this string as below :
String s = "chapterId=c_1§ionId=s_24666&isHL=1&cssFileName=haynes";
or
String s = "chapterId=c_1§ionId=s_24666";
I need to get the number ("24666" in the examples).
String res = s.substring(s.lastIndexOf("s_")+ 2) this returns me the number + chars till the end of the string(the second example is ok). But I need to stop after the number ends. How can I do that.? Thanks
You can use regExp
String s = "chapterId=c_1§ionId=s_24666";
//OR
//String s = "chapterId=c_1§ionId=s_24666&isHL=1&cssFileName=haynes";
s=s.replaceAll(".*?s_(\\d+).*","$1");
System.out.println(s);
OUTPUT:
24666
Where,
.*?s_ means anything before s_ (s_ inclusive)
(\\d+) means one or more digits () used for group
$1 means group 1 which is digits after s_
Note:Assumed that your every string follows specific format which includes s_ and number after s_.
You can split the string by the character & to get the parameters, and split each parameter with the = to get the parameter name and parameter value. And now look for the parameter name "sectionId", and cut the first 2 characters of its value to get the number, and you can use Integer.parseInt() if you need it as an int.
Note that this solution is flexible enough to process all parameters, not just the one you're currently interested in:
String s = "chapterId=c_1§ionId=s_24666&isHL=1&cssFileName=haynes";
String[] params = s.split("&");
for (String param : params) {
String[] nameValue = param.split("=");
if ("sectionId".equals(nameValue[0])) {
int number = Integer.parseInt(nameValue[1].substring(2));
System.out.println(number); // Prints 24666
// If you don't care about other parameters, this will skip the rest:
break;
}
}
Note:
You might want to put Integer.parseInt() into a try-catch block in case an invalid number would be passed from the client:
try {
int number = Integer.parseInt(nameValue[1].substring(2));
} catch (Exception e) {
// Invalid parameter value, not the expected format!
}
Try this:
I use a check in the substring() method - if there is no "&isHL" in the string (meaning its type 2 you showed us), it will just read until the string ends. otherwise, it will cut the string before the "&isHL". Hope this helps.
Code:
String s = "chapterId=c_1§ionId=s_**24666**";
int endIndex = s.indexOf("&isHL");
String answer = s.substring(s.lastIndexOf("s_") + 2, endIndex == -1 ? s.length() : endIndex);
Try following:
String s = "chapterId=c_1§ionId=s_24666&isHL=1&cssFileName=haynes";
String tok[]=s.split("&");
for(String test:tok){
if(test.contains("s_")){
String next[]=test.split("s_");
System.out.println(next[1]);
}
}
Output :
24666
Alternatively you can simply remove all other words if they are not required as below
String s="chapterId=c_1§ionId=s_24666&isHL=1&cssFileName=haynes";
s=s.replaceAll(".*s_(\\d+).*","$1");
System.out.println(s);
Output :
24666
The dig over here is splitting your string using a Regular Expression to further divide the string into parts and get what is required. For more on Regular Expressions visit this link.
You could sue this regex : (?<=sectionId=s_)(\\d+) This uses positive look-behind.
demo here
Following code will work even if there is multiple occurrence of integer in given string
String inputString = "chapterId=c_a§ionId=s_24666&isHL=1&cssFileName=haynes_45";
String[] inputParams = inputString.split("&");
for (String param : inputParams)
{
String[] nameValue = param.split("=");
try {
int number = Integer.parseInt(getStringInt(nameValue[1]));
System.out.println(number);
}
catch(IllegalStateException illegalStateException){
}
}
private String getStringInt(String inputString)
{
Pattern onlyInt = Pattern.compile("\\d+");
Matcher matcher = onlyInt.matcher(inputString);
matcher.find();
String inputInt = matcher.group();
return inputInt;
}
OUTPUT
2466
1
45
Use split method as
String []result1 = s.split("&");
String result2 = tempResult[1];
String []result3 = result2.split("s_");
Now to get your desire number you just need to do
String finalResult = result3[1];
INPUT :
String s = "chapterId=c_1§ionId=s_24666&isHL=1&cssFileName=haynes";
OUPUT :
24666
I have a String that represents a time value and is stored in the following format:
1:31:25
I would like to replace the colons and change the format to:
1h 31m 25s
What function in Java will let me replace the first two colons with 'h ' and 'm ', and the end of the string with 's'.
You could do something like this:
String[] s = myString.split(":");
String.format("%sh %sm %ss", s);
Or even compact!
String.format("%sh %sm %ss", myString.split(":"));
String time = "1:31:25";
String formattedTime = time.replaceFirst(":","h ").replaceFirst(":","m ").concat("s");
String input = "1:31:25";
String[] tokens = input.split(":");
String output = tokens[0] + "h " + tokens[1] + "m " + tokens[2] + "s";
Repeated use of the String.replaceFirst() method would help you here.
Simply replace your first ':' with the 'h', then apply again for 'm' etc.
There are additional options, which may be more appropriate/robust etc. depending on your circumstances.
Regular expressions may be useful here, to help you parse/split up such a string.
Or given that you're parsing/outputting times, it may also be worth looking at SimpleDateFormat and its ability to parse/output date/time combinations.
In fact, if you're storing that date as a string, you may want to revist that decision. Storing it as a date object (of whatever variant) is more typesafe, will protect you against invalid values, and allow you to perform arithmetic etc on these.
String[] timeStr = "1:31:25".split(":");
StringBuffer timeStrBuf = new StringBuffer();
timeStrBuf.append(timeStr[0]);
timeStrBuf.append("h ");
timeStrBuf.append(timeStr[1]);
timeStrBuf.append("m ");
timeStrBuf.append(timeStr[2]);
timeStrBuf.append("s");
You can use a regular expression and substitution:
String input = "1:31:25";
String expr = "(\\d+):(\\d+):(\\d+)";
String substitute = "$1h $2m $3s";
String output = input.replaceAll(expr, substitute);
An alternative is to parse and output the String through Date:
DateFormat parseFmt = new SimpleDateFormat("HH:mm:ss");
DateFormat displayFmt = new SimpleDateFormat("H'h' mm\'m' ss's'");
Date d = parseFmt.parse(input);
output = displayFmt.format(d);
Use split()
String s = "1:31:25";
String[] temp = s.split(":");
System.out.println(s[0]+"h"+" "+s[1]+"m"+" "+s[2]+"s");
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.
I have two strings in a java program, which I want to mix in a certain way to form two new strings. To do this I have to pick up some constituent chars from each string and add them to form the new strings. I have a code like this(this.eka and this.toka are the original strings):
String muutettu1 = new String();
String muutettu2 = new String();
muutettu1 += this.toka.charAt(0) + this.toka.charAt(1) + this.eka.substring(2);
muutettu2 += this.eka.charAt(0) + this.eka.charAt(1) + this.toka.substring(2);
System.out.println(muutettu1 + " " + muutettu2);
I'm getting numbers for the .charAt(x) parts, so how do I convert the chars to string?
StringBuilder builder = new StringBuilder();
builder
.append(this.toka.charAt(0))
.append(this.toka.charAt(1))
.append(this.toka.charAt(2))
.append(' ')
.append(this.eka.charAt(0))
.append(this.eka.charAt(1))
.append(this.eka.charAt(2));
System.out.println (builder.toString());
Just use always use substring() instead of charAt()
In this particular case, the values are mutable, consequently, we can use the built in String class method substring() to solve this problem (#see the example below):
Example specific to the OP's use case:
muutettu1 += toka.substring(0,1) + toka.substring(1,2) + eka.substring(2);
muutettu2 += eka.substring(0,1) + eka.substring(1,2) + toka.substring(2);
Concept Example, (i.e Example showing the generalized approach to take when attempting to solve a problem using this concept)
muutettu1 += toka.substring(x,x+1) + toka.substring(y,y+1) + eka.substring(z);
muutettu2 += eka.substring(x,x+1) + eka.substring(y,y+1) + toka.substring(z);
"...Where x,y,z are the variables holding the positions from where to extract."
The obvious conversion method is Character.toString.
A better solution is:
String muutettu1 = toka.substring(0,2) + eka.substring(2);
String muutettu2 = eka.substring(0,2) + toka.substring(2);
You should create a method for this operation as it is redundant.
The string object instatiantiation new String() is unnecessary. When you append something to an empty string the result will be the appended content.
You can also convert an integer into a String representation in two ways: 1) String.valueOf(a) with a denoting an integer 2) Integer.toString(a)
This thing can adding a chars to the end of a string
StringBuilder strBind = new StringBuilder("Abcd");
strBind.append('E');
System.out.println("string = " + str);
//Output => AbcdE
str.append('f');
//Output => AbcdEf