第一种方法:(最好用)//运用scanner类 /* new是创建一个Scanner类的对象,但是在创建对象时需要用System.in 作为它的参数,也可以将Scanner看作是System.in对象的支持者,System.in取得用户 输入以后,交给Scanner来做一些处理。 Scanner类提供了多个方法: next();取得一个字符串 nextInt();将取得的字符串转换成int型整数 nextFloat();将取得的字符串转换成float型 nextBoolean();将取得的字符串转换成boolean型 注:用Scanner获得用户的输入非常的方便,但是Scanner取得的输入依据是 空格符,包括空格键,Tab键和Enter键,当按下这其中的任一个键时,Scanner 就不能完整的获得你输入的字符串,这时候就要用BufferedReader类取得输入。 */ import java.util.Scanner; public class InputTest { public static Scanner sc; public static void main(String[] args) { sc = new Scanner(System.in); System.out.println("我的姓名是:"); String name = sc.nextLine(); System.out.println("我的年龄是:"); int age = sc.nextInt(); System.out.println("我的工资是:"); float salary = sc.nextFloat(); System.out.println("您的信息如下:"); System.out.println("我的姓名是:" + name + "\n" + "我的年龄是:" + age + "\n" + "我的工资是:" + salary); } }
//从控制台接收一个字符串,然后将其打印出来 /*BufferedReader类位于java.io这个包中,使用BufferedReader对象的readline()方法 获得用户输入,并且必须处理java.io.IOException异常 readline()会返回用户按下Enter键之前的所有字符输入,不包括最后按下的Enter返回字符*/ import java.io.*; public class InputTest { public static void main(String[] args)throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String str = null; System.out.println("请输入你想要的话:"); str = br.readLine(); System.out.println("你输入的是:" + str); } }*/
//利用BufferedReader实现从键盘读入字符串并写进文件Abu.txt import java.io.*; public class InputTest { public static void main(String[] args) throws IOException { BufferedReader rbuf = new BufferedReader(new InputStreamReader(System.in)); BufferedWriter wbuf = new BufferedWriter(new FileWriter("Abu.txt")); String str = rbuf.readLine(); while(!str.equals("exit")) { wbuf.write(str); wbuf.newLine(); str = rbuf.readLine(); } rbuf.close(); wbuf.close(); } }
/*从键盘得到一个字符然后将它打印出来*/ //只能接收一个字符,只能是占一个字节的,汉字占两个字节不可以 import java.io.*; public class InputTest { public static void main(String[] args)throws IOException { System.out.println("请输入一个字符:"); char i = (char)System.in.read(); System.out.println("你输入的是:" + i); } }
/*使用JOptionPane创建输入对话框,实现键盘输入 showConfirmDialog(): 询问一个确认问题,如yes/no/cancer showInputDialog(): 提示要求某些输入 showMessageDialog(): 告知用户某事已经发生 其中,输入对话框的常用参数形式有: showInputDialog(Object message) : message 表提示信息 showInputDialog(Object message,Object initialSelectionValue): 如果没有输入数据,则默认初始值为initalSlectionValue */ import javax.swing.JOptionPane; public class DataInputDialog { public static void main(String[] args) { String str; str = JOptionPane.showInputDialog("input data:"); int num = Integer.parseInt(str); System.out.println(num); } }
原文:http://blog.csdn.net/hxysea/article/details/18323623