當前位置:才華齋>IT認證>JAVA認證>

java的輸入語句小結

JAVA認證 閱讀(1.99W)

Java中做輸入的方式:通過控制檯輸入資料,需要使用Scanner物件來操作,那麼java輸入語句到底有哪些呢?下面跟yjbys小編一起來看看吧!

java的輸入語句小結

  1.使用Scanner

使用時需要引入包import ner;首先定義Scanner物件

Scanner sc = new Scanner();

如果要輸入整數,則 int n = Int();

String型別的,則String temp = ();

比如:

import ner;

public class Test {

public static void main(String[] args) {

Scanner scanner = new Scanner();

int[] days = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};

int month = -1;

while(true) {

try {

t("請輸入月份:");

month = Int();

if(month >= 1 && month <= 12) {

break;

}

tln("** 請輸入正確的.月份 **");

} catch (Exception e) {

tln("** 格式錯誤!請輸入數字 **");

();

}

}

tln(month + " 月份有:" + days[month - 1] + " 天");

}

}

  2.使用BufferedReader

用前需要引入 import er;

BufferedReader br = new BufferedReader( new InputStreamReader() );

String input = Line();

比如:

==================================================================================================

import .*;

public class importtext {

public static void main(String[] args) {

String st;

int num;

float fnum;

try{

t("輸入:");

BufferedReader br=new BufferedReader(new InputStreamReader());

st = Line();

t("輸入一個數:");

num = eInt(Line());

t("輸入一個浮點數:");

fnum = eFloat(Line());

t("輸出:"+st+'n');

t("輸出:"+num+'n');

t("輸出:"+fnum+'n');

}catch(IOException e){}

}

}

==================================================================================================

package com.s2;

import .*;

public class Input

{

public static void main(String[] args)throws IOException

{

while(true)

{

BufferedReader buf;

String str;

buf =new BufferedReader(new InputStreamReader());

tln("Input a string:");

str=Line();

tln("String="+str);

}

}

}

==================================================================================================

應該注意的是:Java把從鍵盤輸入的資料一律看作是字串,因此若要從鍵盤輸入並讓系統認可是數值型資料,必須經過轉換

比如:

package com.s2;

import .*;

public class Input

{

public static void main(String[] args)throws IOException

{

while(true)

{

int num;

BufferedReader buf;

String str;

buf =new BufferedReader(new InputStreamReader());

tln("Input an integer:");

str=Line();

num=eInt(str);

tln("String="+str);

tln("Integer="+str);

}

}

}