JAVA题,将一个字符串的值转换成浮点型(double)数值
发布网友
发布时间:2022-10-13 08:10
我来回答
共2个回答
热心网友
时间:2023-11-01 21:49
import java.io.*;
public class test{
public static void main(String [] args) {
try{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String str = null;
System.out.println("Enter your value:");
str = br.readLine();
System.out.println("your value is :"+str);
int i=Integer.parseInt(str);
System.out.println(i);
}catch(Exception e){
System.exit(0);
}
}
}
热心网友
时间:2023-11-01 21:49
import java.io.*;
class Test{
public static void main(String[] args){
String value=null;
double result=0;
try{
BufferedReader bis =new BufferedReader(new InputStreamReader(System.in));
while((value=bis.readLine())!=null){
DoubleConverter dc= new DoubleConverter();
if(!dc.testDouble(value)) {
System.out.println("输入不是浮点型");
System.exit(-1);
}
else {
result = dc.doConvert(value);
System.out.println("double value:"+result);
}
}
bis.close();
}catch(IOException e){
e.printStackTrace();
}
}
}
class DoubleConverter{
boolean testDouble(String s){
for(int i=0;i<s.length();i++)
if(s.charAt(i)=='d'||s.charAt(i)=='D') return true;
return false;
}
double doConvert(String s)
{
double val = 0;
try{
ByteArrayInputStream s =new ByteArrayInputStream(s.getBytes());
DataInputStream dis = new DataInputStream(s);
val = dis.readDouble();
s.close();
dis.close();
}catch(Exception e)
{
e.printStackTrace();
}
return val;
}
}