上一次說java沒有c++里類似cin這樣的從控制臺讀取的命令,其實不對。今天介紹的Scanner這個類是java 5新增加的類,不僅使用方便,功能更是強大。先來看一個簡單的例子:System.in指明從鍵盤讀入數(shù)據(jù)
import java.util.*;
public class ScannerTest {
import java.util.*;
public class ScannerTest {
public static void main(String[] args){
Scanner scanner=new Scanner(System.in);
double a=scanner.nextDouble();
System.out.println(a);
}
}
Scanner scanner=new Scanner(System.in);
double a=scanner.nextDouble();
System.out.println(a);
}
}
運行
輸入 一個任意數(shù)然后輸出這個數(shù)
注意粗體字的地方,這一行就實現(xiàn)了從控制臺輸入數(shù)字的功能,如果要從鍵盤輸入字符串可以用:
String a=scanner.next();//注意不是nextString()
Scanner還可以直接掃描文件,比如(有點長,耐心一點)??梢灾付ㄆ渌斎肓鞯膶ο?如FileInputStream的對象,這樣的話就是從文件里讀入數(shù)據(jù),而不是從鍵盤讀入
import java.util.*;
import java.io.*;
public class ScannerTest {
public static void main(String[] args) throws IOException{//這里涉及到文件io操作
double sum=0.0;
int count=0;
FileWriter fout=new FileWriter("text.txt");
fout.write("2 2.2 3 3.3 4 4.5 done");//往文件里寫入這一字符串
fout.close();
FileReader fin=new FileReader("text.txt");
Scanner scanner=new Scanner(fin);//注意這里的參數(shù)是FileReader類型的fin
while(scanner.hasNext()){//如果有內(nèi)容
if(scanner.hasNextDouble()){//如果是數(shù)字
sum=sum+scanner.nextDouble();
count++;
}else{
String str=scanner.next();
if(str.equals("done")){
break;
}else{
System.out.println("文件格式錯誤!");
return;
}
}
}
fin.close();
System.out.println("文件中數(shù)據(jù)的平均數(shù)是:"+sum/count);
}
}
import java.io.*;
public class ScannerTest {
public static void main(String[] args) throws IOException{//這里涉及到文件io操作
double sum=0.0;
int count=0;
FileWriter fout=new FileWriter("text.txt");
fout.write("2 2.2 3 3.3 4 4.5 done");//往文件里寫入這一字符串
fout.close();
FileReader fin=new FileReader("text.txt");
Scanner scanner=new Scanner(fin);//注意這里的參數(shù)是FileReader類型的fin
while(scanner.hasNext()){//如果有內(nèi)容
if(scanner.hasNextDouble()){//如果是數(shù)字
sum=sum+scanner.nextDouble();
count++;
}else{
String str=scanner.next();
if(str.equals("done")){
break;
}else{
System.out.println("文件格式錯誤!");
return;
}
}
}
fin.close();
System.out.println("文件中數(shù)據(jù)的平均數(shù)是:"+sum/count);
}
}
結(jié)果輸出文件中數(shù)據(jù)的平均數(shù)是:3.1666666666666665
這段程序的功能是將"2 2.2 3 3.3 4 4.5 done"寫入文件scanner讀取文件中的數(shù)直到done結(jié)束。并求出數(shù)字的平均值,比較有意思的是scanner會自動一空格作為分割符區(qū)分不同數(shù)字。當然也可以通過scanner.useDelimiter(Pattern pattern)來設(shè)置不同的分割符,比如 scanner.useDelimiter(",*");
這段程序的功能是將"2 2.2 3 3.3 4 4.5 done"寫入文件scanner讀取文件中的數(shù)直到done結(jié)束。并求出數(shù)字的平均值,比較有意思的是scanner會自動一空格作為分割符區(qū)分不同數(shù)字。當然也可以通過scanner.useDelimiter(Pattern pattern)來設(shè)置不同的分割符,比如 scanner.useDelimiter(",*");
如果你感興趣,更多強大的功能可以參看jdk 5 的幫助文檔
本文出自 “Xhinker” 博客,請務(wù)必保留此出處http://xhinker.blog.51cto.com/640011/133575
ExtJS教程- Hibernate教程-Struts2 教程-Lucene教程