从混合文件中读取双数字 [英] Reading double numbers from mixed file
本文介绍了从混合文件中读取双数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
public void doubleFromFile()
{
扫描仪扫描=新扫描仪(System.in);
扫描仪fileScan;
布尔值validName = false;
double num = 0.0;
do
{
System.out.print(Enter file name:);
String str = scan.nextLine();
try
{
fileScan = new Scanner(new File(str));
validName = true;
而(fileScan.hasNextLine())
{
尝试
{
海峡= fileScan.nextLine() ;
num = Double.parseDouble(str);
System.out.println(str);
catch(NumberFormatException nfe)
{
System.out.println(不是双数);
}
} // end while
} //结束尝试
catch(FileNotFoundException fnfe)
{
System.out.println(Invalid File name:enter again); $!
$ b} while(!validName);
} //结束doubleFromFile方法
解决方案
这是一个工作测试 Scanner sc = new Scanner(aaaa 1.1 bbb\\\
3);
sc.useLocale(Locale.US);
while(sc.hasNext()){
if(sc.hasNextDouble()){
System.out.println(sc.nextDouble());
} else {
sc.next();
请注意,我使用了美国语言环境, 。作为小数点分隔符,在我的语言环境中(默认)是,。还要注意,1.1和3(整数)都被nextDouble
识别
Trying to read double numbers only where the file contains numbers and words. Code i have done so far reads from file properly and prints full list with numbers and words. Not sure how to exclude words and print read only double numbers.
public void doubleFromFile()
{
Scanner scan = new Scanner(System.in);
Scanner fileScan;
boolean validName = false;
double num = 0.0;
do
{
System.out.print("Enter file name: ");
String str = scan.nextLine();
try
{
fileScan = new Scanner(new File(str));
validName = true;
while(fileScan.hasNextLine())
{
try
{
str = fileScan.nextLine();
num = Double.parseDouble(str);
System.out.println(str);
}
catch (NumberFormatException nfe)
{
System.out.println("is not a Double number");
}
}//end while
}// end try
catch (FileNotFoundException fnfe)
{
System.out.println("Invalid File name: enter again");
}
}while(!validName);
}//end doubleFromFile method
解决方案 Here is a working test
Scanner sc = new Scanner("aaaa 1.1 bbb\n3");
sc.useLocale(Locale.US);
while (sc.hasNext()) {
if (sc.hasNextDouble()) {
System.out.println(sc.nextDouble());
} else {
sc.next();
}
}
Note that I used US locale so that Scanner interpets "." as decimal separator, in my locale (default) it is ",". Also note that both 1.1 and 3 (integer) are recognized by nextDouble
这篇关于从混合文件中读取双数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文