使用Main方法的參數傳遞方式
例示代碼如下:
public class MainArgs
{
public static void main(String[] args)
{
System.out.println(args.length);
for(String str : args){
System.out.println(str);
}
}
}
在運行 java程序后面跟的字符串(一個或多個 多個用空格隔開)jvm將會把這些一個或多個字符串賦給args數組。當字符串中包含空格時則需要將完整的一個字符串用“”括起來。如下示例:
使用Scanner類進行用戶輸入:可以輸入用戶指定的數據類型
Scanner 使用分隔符模式將其輸入分解為標記,默認情況下該分隔符模式與空白匹配。然后可以使用不同的 next 方法將得到的標記轉換為不同類型的值。
例示代碼如下:
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);
}
//讀取任何的數據輸入返回String
public static void test1(){
Scanner scan = new Scanner(System.in);
//使用 回車鍵 作為分隔符 默認使用 空格 制表鍵 回車作為分割付。
//scan.useDelimiter("\n");
while(scan.hasNext()){
System.out.println("next is " + scan.next());
}
}
//讀取Long型數據的輸入返回Long
public static void test2(){
Scanner scan = new Scanner(System.in);
//當輸入的為 非 Long數值時 推出循環
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....");
}
}
//讀取文件中的內容 并打印到控制臺
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);
}
}
}