使用Main方法的參數(shù)傳遞方式
例示代碼如下:
public class MainArgs
{
public static void main(String[] args)
{
System.out.println(args.length);
for(String str : args){
System.out.println(str);
}
}
}
在運(yùn)行 java程序后面跟的字符串(一個(gè)或多個(gè) 多個(gè)用空格隔開)jvm將會(huì)把這些一個(gè)或多個(gè)字符串賦給args數(shù)組。當(dāng)字符串中包含空格時(shí)則需要將完整的一個(gè)字符串用“”括起來。如下示例:
使用Scanner類進(jìn)行用戶輸入:可以輸入用戶指定的數(shù)據(jù)類型
Scanner 使用分隔符模式將其輸入分解為標(biāo)記,默認(rèn)情況下該分隔符模式與空白匹配。然后可以使用不同的 next 方法將得到的標(biāo)記轉(zhuǎn)換為不同類型的值。
例示代碼如下:
import java.util.Scanner;
import java.io.File;
public class ScannerKeyBoardTest
{
public static void main(String[] args) throws Exception
{
//readFileCon();
//test2();
//通過鍵盤輸入指定類型
Scanner scan = new Scanner(System.in);
Long l = scan.nextLong();
System.out.println("l is "+l);
}
//讀取任何的數(shù)據(jù)輸入返回String
public static void test1(){
Scanner scan = new Scanner(System.in);
//使用 回車鍵 作為分隔符 默認(rèn)使用 空格 制表鍵 回車作為分割付。
//scan.useDelimiter("\n");
while(scan.hasNext()){
System.out.println("next is " + scan.next());
}
}
//讀取Long型數(shù)據(jù)的輸入返回Long
public static void test2(){
Scanner scan = new Scanner(System.in);
//當(dāng)輸入的為 非 Long數(shù)值時(shí) 推出循環(huán)
while(scan.hasNextLong()){//阻塞式
//System.out.println("has over scan.nextLong() begin....");
System.out.println("next is " + scan.nextLong());
//System.out.println("scan.nextLong() over has begin....");
}
}
//讀取文件中的內(nèi)容 并打印到控制臺(tái)
public static void readFileCon()throws Exception
{
Scanner scan = new Scanner(new File("ScannerKeyBoardTest.java"));
System.out.println("fileContent is:");
while(scan.hasNextLine()){
System.out.println(scan.nextLine());
}
}
}
使用BufferedReader類讀取用戶的輸入:返回的只能是String類
例示代碼如下
import java.io.BufferedReader;
import java.io.InputStreamReader;
class BufferReaderKeyBoardTest
{
public static void main(String[] args) throws Exception
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String in = null;
while((in = br.readLine()) != null){
System.out.println("用戶輸入的是: "+in);
}
}
}