java的輸入語句小結
Java中做輸入的方式:通過控制枱輸入數據,需要使用Scanner對象來操作,那麼java輸入語句到底有哪些呢?下面跟yjbys小編一起來看看吧!
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);
}
}
}
-
2016年Java認證筆試題及答案
一、單項選擇題是從()語言改進重新設計。B.C++calC答案:B2.下列語句哪一個正確()A.Java程序經編譯後會產生machinecode程序經編譯後會產生bytecode程序經編譯後會產生DLLD.以上都不正確答案:B3.下列説法正確的有()s中的constructor不可省略B.constructor必須與cl...
-
Java應用註冊後台服務
項目中有一個java應用程序,交付後用户要求要把這個程序做成後台服務程序,即:系統啟動後該程序可以自動啟動,並且在前台不要出現運行窗口,維護人員只要在服務管理(Windows)中選擇啟動或停止即可.解決辦法如下:Linux在Linux中註冊後台服務程序相對容易,只需編輯/etc/ini...
-
Java的位運算符和邏輯運算符
在許多古老的微處理器上,位運算比加減運算略快,通常位運算比乘除法運算要快很多。在現代架構中,情況並非如此:位運算的運算速度通常與加法運算相同(仍然快於乘法運算).下面小編準備了關於Java的位運算符和邏輯運算符,提供給大家參考!一.與、或、非、異或運算與0&am...
-
Spring創建Bean過程的方法
1.beans包提供了以編程方式管理和操作bean的基本功能,而context包增加了ApplicationContext,它以一種更加面向框架的方式增強了BeanFactory的功能。2.context包的基礎是位於ext包中的ApplicationContext接口。它是由BeanFactory接口派生而來的,提供了BeanFactory...