java中怎样从一系列字符串中读取小数?例如14.2、0.0
java中怎样从一系列字符串中读取小数?例如14.2、0.0
------解决方案--------------------import java.util.*;
public class Fenxi
{
public static void main(String args[])
{
String str = "we are students 14.2,0.0 ";
StringTokenizer fenxi= new StringTokenizer(str, " , "); //以空格和逗号分
int len = fenxi.countTokens();
while(fenxi.hasMoreTokens())
{
String s = fenxi.nextToken();
StringBuffer temps = new StringBuffer();
char sr[] = s.toCharArray();
for(int i = 0;i <sr.length;i++)
{
if(Character.isDigit(sr[i]) || (sr[i] == '. '))
temps.append(sr[i]);
}
if(temps.length() != 0)
System.out.println( " " + new String(temps));
}
}
}
临时写了一个,也满足要求了,嘿嘿
------解决方案--------------------import java.util.*;
public class Fenxi
{
public static void main(String args[])
{
String str = "we are students 14.2,0.0 ";
StringTokenizer fenxi= new StringTokenizer(str, " , "); //以空格和逗号分
int len = fenxi.countTokens();
while(fenxi.hasMoreTokens())
{
String s = fenxi.nextToken();
StringBuffer temps = new StringBuffer();
char sr[] = s.toCharArray();
for(int i = 0;i <sr.length;i++)
{
if(Character.isLetter(sr[i]))
{
System.out.println( "字符串: " + s);
break;
}
else if(Character.isDigit(sr[i]) || (sr[i] == '. '))
temps.append(sr[i]);
}
if(temps.length() != 0)
System.out.println( "数字: " + new String(temps));
}
}
}
------解决方案--------------------public class Test {
public static void main(String[] args){
String str = "abc32.45 <> 1.42**.11222YY0.Xaab12.999.+0.9&bbc ";
List numbers = new ArrayList();
StringBuilder sb = new StringBuilder(str);
while(sb.indexOf( ". ") > = 0) {
StringBuilder sbFront = getFront(sb);
StringBuilder sbEnd = getEnd(sb);
if (sbFront.length() > 0 && sbEnd.length() > 0) {
numbers.add(sbFront.append( ". ").append(sbEnd));
}
}
for(Object obj : numbers) {
System.out.println(obj);
}
}
private static StringBuilder getFront(StringBuilder sb) {
//handle the front
StringBuilder strb = new StringBuilder();
for(int i = sb.indexOf( ". ") - 1; i > 0; i--) {
if(Character.isDigit(sb.charAt(i))) {
strb.insert(0, sb.charAt(i));
} else {
break;
}
}
return strb;
}
private static StringBuilder getEnd(StringBuilder sb) {
//handle the end
StringBuilder strb = new StringBuilder();
int i = 0;
for(i = sb.indexOf( ". ") + 1; i > 0; i++) {
if(Character.isDigit(sb.charAt(i))) {
strb.append(sb.charAt(i));
} else {
break;
}
}
//delete the string
sb.delete(0, i);
return strb;
}
}