Java鍵盤輸入實例
- java語言
- 關注:1.48W次
引導語:java不像C中擁有scanf這樣功能強大的函數,大多是通過定義輸入輸出流對象,以下是本站小編分享給大家的Java鍵盤輸入實例,歡迎閲讀!
import ner;
/**
* 測試從鍵盤讀取用户的.輸入,關鍵類為Scanner
* @author Administrator
*
*/
public class TestInput {
public static void main(String[] args) {
Scanner s = new Scanner();
tln("請輸入你的姓名:");
String name = Line();
tln("請輸入你的年齡:");
int age = Int();
tln("請輸入你的工資:");
float salary = Float();
tln("你的信息如下:");
tln("姓名:"+name+"n"+"年齡:"+age+"n"+"工資:"+salary);
}
}
説明:Scanner的對象的方法nextLine()接收字符和字符串類型的輸入;nextInt()接收int類型的;nextFloat()接收float類型的,相信後面的就不用一一列舉了吧。
方法2:
BufferedReader reader=new BufferedReader(new InputStreamReader());
t("Please input a number:");
String str=Line(); //獲取字符串
tln("The number you input is:"+str);
或
InputStreamReader reader = new InputStreamReader();
BufferedReader input = new BufferedReader(reader);
t("Enter your age: ");
String text = Line();
int age = new Integer(text)alue();
tln("You are " + age + " years old, now,");
int year = 2003 - age;
tln("so you were probably born in " + year);
需要拋出io異常。
import .*;
- @5 n0 _4 H: c( y: Hclass JavaIO_02N {' U- 9 P1 S, C2 m- R3 p& t
public static void main(String param[])
# u P+ ]+ a2 L6 O! V {: B7 A6 r3 ^ [4 ~
String nn1="";//定義一個String整型對象nn1: b5 T) n6 E9 f4 @9 p
BufferedReader distream = new BufferedReader(new InputStreamReader());
, p1 J D/ B, @1 L" q6 P' a tln("鍵入一個整數"); r& m/ H2 s' Q h" T( |+ j
nn1=Line();//進行輸入,並把輸入的數存入nn1中/ l, u4 y3 e5 R
) J+ D7 n$ u; z% v3 Z7 g# S* w0 l int n1=eInt(nn1);( z4 l# |( L/ q
if(n1%2==0)
. C6 b9 U$ D* F( y! K tln(n1+"是一個偶數");
3 ?! ^" c% C9 ], i- G9 L9 }/ b else( u- G, Z( Z* { V# _; _0 O
tln(n1+"是一個奇數"); 2 _; b) N, Q2 4 W9 D: y$ t! E5 ~# J
}% c! z' y( d6 d/ v# {. _7 Q
}
1 F: w6 M1 H) |8 j) O: e' C4 e
& v" }5 S9 }& Y& l8 B
" f9 G8 K, H+ A6 P% ajava不可能出現語句在任何方法,類之外的
/* * Created on 2005-4-5
* * TODO To change the template for this generated file go to
* Window - Preferences - Java - Code Style - Code Templates
*/
import eredReader;
import ception;
import tStreamReader;
/**
* @author Zhangql
*
* TODO To change the template for this generated type comment go to
* Window - Preferences - Java - Code Style - Code Templates
*/
public class EnterConsole
{
public static void main(String[] args) throws IOException
{
EnterConsole enterConsole = new EnterConsole();
tConsoleChar();
}
/**
* 從控制對接收一行字符串,然後輸出到控制枱
* @throws IOException
*/
public void printConsoleLine() throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader());
String str = null;
tln("Enter your value:");
str = Line();
tln("your value is :"+str);
}
/**
* 從控制枱接收一個字符
* 然後打印到控制枱上
* @throws IOException
*/
public void printConsoleChar() throws IOException
{
t("Enter a Char:");
char i = (char) ();
tln("your char is :"+i);
}
}
- 文章版權屬於文章作者所有,轉載請註明 https://xuezhezhai.com/zh-mo/jsj/java/rx95g.html